package com.hnkywl.sts.service.xsgl;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.hnkywl.sts.dao.base.ClxxDao;
import com.hnkywl.sts.dao.base.JkpzDao;
import com.hnkywl.sts.dao.base.SjzdzDao;
import com.hnkywl.sts.dao.cggl.CgdDao;
import com.hnkywl.sts.dao.cggl.GlfyDao;
import com.hnkywl.sts.dao.djgl.GoodsesDao;
import com.hnkywl.sts.dao.djgl.JyddDao;
import com.hnkywl.sts.dao.htgl.CghtDao;
import com.hnkywl.sts.dao.htgl.HtmxDao;
import com.hnkywl.sts.dao.htgl.XshtDao;
import com.hnkywl.sts.dao.jhgl.QueryContractDao;
import com.hnkywl.sts.dao.jsgl.XsjsdDao;
import com.hnkywl.sts.dao.jsgl.XsjsdmxDao;
import com.hnkywl.sts.dao.jsgl.ZjbcdDao;
import com.hnkywl.sts.dao.jsgl.ZjbcdRzDao;
import com.hnkywl.sts.dao.organ.CkDao;
import com.hnkywl.sts.dao.organ.EjzhDao;
import com.hnkywl.sts.dao.organ.GsjgDao;
import com.hnkywl.sts.dao.sfgl.SkshDao;
import com.hnkywl.sts.dao.shgl.AblbzjshDao;
import com.hnkywl.sts.dao.shgl.DlfDao;
import com.hnkywl.sts.dao.shgl.WbzjshDao;
import com.hnkywl.sts.dao.sys.GgDao;
import com.hnkywl.sts.dao.sys.KhjwhDao;
import com.hnkywl.sts.dao.sys.ZdkhzDao;
import com.hnkywl.sts.dao.xsgl.*;
import com.hnkywl.sts.dao.zjfp.ZjfpmxDao;
import com.hnkywl.sts.dao.zjgl.BzjDao;
import com.hnkywl.sts.dao.zjgl.HthkDao;
import com.hnkywl.sts.entity.base.Clxx;
import com.hnkywl.sts.entity.base.Jkpz;
import com.hnkywl.sts.entity.base.Sjzdz;
import com.hnkywl.sts.entity.cggl.*;
import com.hnkywl.sts.entity.djgl.Goodses;
import com.hnkywl.sts.entity.djgl.Jydd;
import com.hnkywl.sts.entity.htgl.Cght;
import com.hnkywl.sts.entity.htgl.Xsht;
import com.hnkywl.sts.entity.organ.*;
import com.hnkywl.sts.entity.sfgl.Sfk;
import com.hnkywl.sts.entity.shgl.Ablbzjgk;
import com.hnkywl.sts.entity.shgl.Dlf;
import com.hnkywl.sts.entity.shgl.Wbzjgk;
import com.hnkywl.sts.entity.sys.Gg;
import com.hnkywl.sts.entity.sys.Khjwh;
import com.hnkywl.sts.entity.sys.Zdkhz;
import com.hnkywl.sts.entity.xsgl.*;
import com.hnkywl.sts.entity.zjfb.Zjfpmx;
import com.hnkywl.sts.entity.zjgl.Hthk;
import com.hnkywl.sts.service.base.BmService;
import com.hnkywl.sts.service.base.SjzdzService;
import com.hnkywl.sts.service.base.WebserviceTransService;
import com.hnkywl.sts.service.kcgl.CkshService;
import com.hnkywl.sts.service.sfgl.SkshService;
import com.hnkywl.sts.service.sys.YgService;
import com.hnkywl.sts.util.CalcUtils;
import com.hnkywl.sts.util.DateUtil;
import com.hnkywl.sts.util.ReflectionUtils;
import com.hnkywl.sts.util.Tools;
import net.ruixin.orm.hibernate.Page;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: jerry
 * Date: 13-4-15
 * Time: 下午2:15
 * To change this template use File | Settings | File Templates.
 */
@Service
public class XsdService {
    private XsdDao xsdDao;

    private CgdDao cgdDao;

    private DfkxsdDao dfkxsdDao;

    private CghtDao cghtDao;

    private QueryContractDao queryContractDao;

    private SjzdzService sjzdzService;

    private JfmxDao jfmxDao;

    private KhDao khDao;

    private GlfyDao glfyDao;

    private SjzdzDao sjzdzDao;

    private XsmxDao xsmxDao;

    private XsjsdDao xsjsdDao;

    private XsjsdmxDao xsjsdmxDao;

    private GgDao ggDao;

    private CkDao ckDao;

    private GdDao gdDao;

    private TkmxDao tkmxDao;

    // 资金分配明细
    private ZjfpmxDao zjfpmxDao;

    private ZjbcdDao zjbcdDao;
    private ZjbcdRzDao zjbcdRzDao;

    private GsjgDao gsjgDao;
    private SkshService skshService;

    private WebserviceTransService webserviceTransService;

    private EjzhDao ejzhDao;
    private BmService bmService;
    private SkshDao skshDao;
    private ShjDao shjDao;
    private KhjwhDao khjwhDao;
    private ZdkhzDao zdkhzDao;
    private JkpzDao jkpzDao;
    private CkshService ckshService;
    private WbzjshDao wbzjshDao;
    private BzjDao bzjDao;
    private DlfDao dlfDao;
    private HthkDao hthkDao;
    private AblbzjshDao ablbzjshDao;
    private JfmxDeteleDao jfmxDeteleDao;
    private JyddDao jyddDao;
    private GoodsesDao goodsesDao;
    private XshtDao xshtDao;
    private HtmxDao htmxDao;
    private ClxxDao clxxDao;


    public String findAllXsd(String xsdh, Date fhsjStart, Date fhsjEnd, Long xshtId, Long khId, Long gcId, Long sbgsId, Long sbbmId, Long sbrId, String zt, String cxzt, String sftzd, String xslx, Boolean dlkhxsd, int type, int pageNo, int pageSize) throws ParseException {
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
        Page xsdPage = this.xsdDao.findXsdList(xsdh, fhsjStart, fhsjEnd, xshtId, khId, gcId, sbgsId, sbbmId, sbrId, zt, cxzt, sftzd, xslx, dlkhxsd, type, pageNo, pageSize);
        String xsdJson = gson.toJson(xsdPage.getResult());
        List<Map> sumList = this.xsdDao.findSumXsd(xsdh, fhsjStart, fhsjEnd, xshtId, khId, gcId, sbgsId, sbbmId, sbrId, zt, cxzt, sftzd, xslx, dlkhxsd, type);
        Double xsjs = 0d;
        Double xssl = 0d;
        Double xsje = 0d;
        Double gylfyje = 0d;
        if (sumList.size() != 0) {
            for (Map map : sumList) {
                xsjs += Double.valueOf((map.get("xsjs") == null ? 0d : map.get("xsjs")).toString());
                xssl += Double.valueOf((map.get("xssl") == null ? 0d : map.get("xssl")).toString());
                xsje += Double.valueOf((map.get("xsje") == null ? 0d : map.get("xsje")).toString());

                gylfyje += Double.valueOf((map.get("gylfyje") == null ? 0d : map.get("gylfyje")).toString());
            }
            return "{\"total\":" + xsdPage.getTotalCount() + ",\"rows\":" + xsdJson + ",\"footer\":[{\"xsdh\":\"合计:\",\"xsjs\":" + xsjs + ",\"xssl\":" + xssl + ",\"xsje\":" + xsje + ", \"gylfyje\":" + gylfyje + " }]}";
        } else {
            return "{\"total\":" + xsdPage.getTotalCount() + ",\"rows\":" + xsdJson + "}";
        }
    }

    public String findXsdByXsht(String xsdh, Date fhsjStart, Date fhsjEnd, Long xshtId, Long khId, Long gcId, Long sbgsId, Long sbbmId, Long sbrId, String zt, String cxzt, String sftzd, String xslx, Boolean dlkhxsd, int pageNo, int pageSize) throws ParseException {
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
        Page xsdPage = this.xsdDao.findXsdByXshtList(xsdh, fhsjStart, fhsjEnd, xshtId, khId, gcId, sbgsId, sbbmId, sbrId, zt, cxzt, sftzd, xslx, dlkhxsd, pageNo, pageSize);
        String xsdJson = gson.toJson(xsdPage.getResult());

        return "{\"total\":" + xsdPage.getTotalCount() + ",\"rows\":" + xsdJson + "}";

    }

    /**
     * 首页显示销售单数
     *
     * @return
     */
    public String findAllXsd() {
        return this.xsdDao.findAllXsd();
    }


    /**
     * 保供销售收入，首页图表显示
     *
     * @param htType
     * @return
     */
    public String findYwsr(String htType) {
        try {
            StringBuffer xsdSb = new StringBuffer();
            Calendar cal = Calendar.getInstance();
            int year = cal.get(Calendar.YEAR);
            xsdSb.append("[");
            for (int i = 1; i <= 12; i++) {
                String month = "";
                if (i < 10) {
                    month = "0" + i;
                }
                // 查询日期保供业务收入
                String sdate = year + "-" + month;
                List bgywsrList = this.xsdDao.findYwsr(sdate, htType);
                if (null != bgywsrList && bgywsrList.size() > 0) {
                    xsdSb.append(bgywsrList.get(0));
                }
                if (i != 0) {
                    xsdSb.append(",");
                }

            }
            xsdSb.append("]");
            return xsdSb.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Transactional
    public String findXsdSearch(String xsdh, Date fhsjStart, Date fhsjEnd, Long xsjsdId, Long xsgsId, Long sbgsId, Long khId, int pageNo, int pageSize, String erdwMc, String htbmStr, String xhtbm) {
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
        Page xsdPage = this.xsdDao.findXsdSearch(xsdh, fhsjStart, fhsjEnd, xsjsdId, xsgsId, sbgsId, khId, pageNo, pageSize, erdwMc, htbmStr, xhtbm);
        String xsdJson = gson.toJson(xsdPage.getResult());
        return "{\"total\":" + xsdPage.getTotalCount() + ",\"rows\":" + xsdJson + "}";
    }

    public String findXsdSearchDate(String xsdh, Date fhsjStart, Date fhsjEnd, Long xsjsdId, Long xsgsId, Long sbgsId, Long khId, int pageNo, int pageSize, String erdwMc) {
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
        Page daXsdPage = this.xsdDao.findXsdDateSearch(xsdh, fhsjStart, fhsjEnd, xsjsdId, xsgsId, sbgsId, khId, 1, 999999999, erdwMc);
        String xsdDateJson = gson.toJson(daXsdPage.getResult());
        return "{\"total\":" + daXsdPage.getTotalCount() + ",\"rows\":" + xsdDateJson + "}";
    }

    @Transactional
    public String findAllXsdNotFyzr(Long thckId, String xspsKh, Long sbgsId, String pszt, String xsdh, String psdh, int pageNo, int pageSize) {
        Sjzdz fyzr = sjzdzDao.getSjzdzByBz("配送");
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
        Page xsdPage = this.xsdDao.findXsdXspsList(thckId, xspsKh, sbgsId, pszt, xsdh, psdh, fyzr, pageNo, pageSize);
        String xsdJson = gson.toJson(xsdPage.getResult());
        return "{\"total\":" + xsdPage.getTotalCount() + ",\"rows\":" + xsdJson + "}";
    }

    @Transactional
    public String findXsdmxSearch(Long xsjsdId) {
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
        List<Map> xsdmxList = this.xsdDao.findXsdmxSearch(xsjsdId);
        return gson.toJson(xsdmxList);
    }

    public String computerPrice(String khIds) {
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        String[] khIdArray = khIds.split(",");
        for (int i = 0; i < khIdArray.length; i++) {
            list.add(shjDao.calculate(Long.valueOf(khIdArray[i])));
        }
        return new Gson().toJson(list);
    }

    @Transactional
    public String findXsdmxSearchDetail(Long xsjsdId) {
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
        java.text.DecimalFormat df = new java.text.DecimalFormat("0.00");
        String result = "";
        Double sl = 0d;
        Double sjghje = 0d;
        Double se = 0d;
        Double je = 0d;
        Double tx = 0d;
        Double dlf = 0d;
        Double zjzyf = 0d;
        Double xkyh = 0d;
        Double fpse = 0d;
        List<Map> xsdmxList;
        Jsd xsjsd = this.xsjsdDao.get(xsjsdId);
        if (xsjsd.getZt() == 3) {
            xsdmxList = this.xsjsdmxDao.findXsjsdmxSearch(xsjsdId);
        } else
            xsdmxList = this.xsdDao.findXsdmxSearch(xsjsdId);
        if (xsdmxList.size() > 0) {
            for (Map map : xsdmxList) {
                sl += map.get("ck_sbsl") == null ? 0d : Double.parseDouble(map.get("ck_sbsl").toString());
                sjghje += map.get("sjghje") == null ? 0d : Double.parseDouble(map.get("sjghje").toString());
                se += map.get("se") == null ? 0d : Double.parseDouble(map.get("se").toString());
                je += map.get("je") == null ? 0d : Double.parseDouble(map.get("je").toString());
                tx += map.get("txx") == null ? 0d : Double.parseDouble(map.get("txx").toString());
                dlf += map.get("dlf") == null ? 0d : Double.parseDouble(map.get("dlf").toString());
                zjzyf += map.get("zjzyf") == null ? 0d : Double.parseDouble(map.get("zjzyf").toString());
                xkyh += map.get("xkyh") == null ? 0d : Double.parseDouble(map.get("xkyh").toString());
                fpse += map.get("fpse") == null ? 0d : Double.parseDouble(map.get("fpse").toString());
            }
            result = "{\"rows\":" + gson.toJson(xsdmxList) + ",\"footer\":[{\"xsdh\":" + "\"合计：\""
                    + ",\"ck_sbsl\":" + df.format(sl) + ", \"sjghje\":" + df.format(sjghje) + ", \"txx\":" +
                    df.format(tx) + ", \"dlf\":" + df.format(dlf) + ", \"zjzyf\":" + df.format(zjzyf) + ", \"xkyh\":" + df.format(xkyh) +
                    ", \"se\":" + df.format(se) + ", \"je\":" + df.format(je) + ", \"fpse\":" + df.format(fpse) + "}]}";
        } else {
            result = "{\"rows\":" + gson.toJson(xsdmxList) + "}";
        }
        return result;
    }

    public Map<String, Object> findXsdmxExp(Long xsjsdId) {
        Map<String, Object> r = new HashMap<String, Object>();
        java.text.DecimalFormat df = new java.text.DecimalFormat("0.00");
        String result = "";
        Double ddfy = 0d;
        Double me = 0d;
        Double je = 0d;
        Double se = 0d;
        List<Map> xsdmxList = this.xsdDao.findXsdmxSearch(xsjsdId);
        r.put("rows", xsdmxList);
        if (xsdmxList.size() > 0) {
            for (Map map : xsdmxList) {
                ddfy += map.get("ddfy") == null ? 0d : Double.parseDouble(map.get("ddfy").toString());
                je += map.get("je") == null ? 0d : Double.parseDouble(map.get("je").toString());
                se += map.get("se") == null ? 0d : Double.parseDouble(map.get("se").toString());
            }
            Map sum = new HashMap();
            sum.put("ddyf", df.format(ddfy));
            sum.put("je", df.format(je));
            sum.put("se", df.format(se));
            sum.put("me", df.format(je + se));
            r.put("sum", sum);
        } else {
            Map sum = new HashMap();
            sum.put("ddyf", df.format(0));
            sum.put("je", df.format(0));
            sum.put("se", df.format(0));
            sum.put("me", df.format(0));
            r.put("sum", sum);
        }
        return r;
    }

    /**
     * 查询销售单
     *
     * @param xsdId 销售单ID
     * @return
     */
    public Xsd findXsdDetail(Long xsdId) {
        return this.xsdDao.get(xsdId);
    }

    public Xsd findByXsdh(String xsdh) {
        return this.xsdDao.findUniqueByProperty("xsdh", xsdh);
    }


    public Xsmx findXsmxByJtwz(Xsd xsd, Kh kh) {
        String hql = "from Xsmx where xsd.id=? and kh.id=?";
        return (Xsmx) this.xsmxDao.findUnique(hql, xsd.getId(), kh.getId());
    }

    public String findXsdJszt(Xsd xsd) {
        String jszt = StringUtils.EMPTY;
        for (int i = 0; i < xsd.getXsmxList().size(); i++) {
            Xsmx xsmx = xsd.getXsmxList().get(i);
            if (i == 0) {
                if (xsmx.getYjs() == null || !xsmx.getYjs()) {
                    jszt = "未结算";
                } else {
                    jszt = "已结算";
                }
            } else {
                if (jszt.equals("未结算") && xsmx.getYjs()) {
                    jszt = "部分结算";
                    break;
                } else if (jszt.equals("已结算") && (xsmx.getYjs() == null || !xsmx.getYjs())) {
                    jszt = "部分结算";
                    break;
                }
            }
        }
        return jszt;
    }

    /**
     * 财务审核销售单
     *
     * @param xsdId
     */
    @Transactional
    public void examineXsd(Long xsdId) {
        Xsd xsd = this.xsdDao.get(xsdId);
        xsd.setCwsh(true);
        xsd.setShsj(new Date());
        xsd.setZt("ysh");
        xsd.setLastUpdated(new Date());
        xsd.setShr(YgService.getCurrentYg());
        this.xsdDao.save(xsd);
    }

    /**
     * 查询全部代理费和贴息（保证金）
     *
     * @param xsd
     * @return
     */
    public Map findMapDlfOrTx(Xsd xsd) {
        Map map = this.jfmxDao.findMapDlfOrTx(xsd.getXsht().getId());
        return map;
    }

    /**
     * // 未付款的代理费
     *
     * @param xsd
     * @return
     */
    public Map findMapWfkDlfOrTx(Xsd xsd) {
        Map map = this.jfmxDao.findMapWfkDlfOrTx(xsd.getXsht().getId());
        return map;
    }


    /**
     * @param xsd
     * @return
     */
    public List<Map> findMapHthk(Xsd xsd) {
        List<Map> mapList = this.jfmxDao.findMapHthk(xsd.getXsht());
        return mapList;
    }

    /**
     * 查询当前代理费和贴息
     *
     * @param xsd
     * @return
     */
    public Map findDqDlfOrTx(Xsd xsd) {
        Map map = this.jfmxDao.findDqDlfOrTx(xsd.getId());
        return map;
    }

    /**
     * 查询资金占用金额
     *
     * @param xsd
     * @return
     */
    public Double findZjzyje(Xsd xsd) {
        Double zjzyje = this.xsdDao.findZjzyje(xsd);
        return zjzyje;
    }

    /**
     * 检查货款是否满足赎货金额
     *
     * @param xsdId
     * @param sfkIds
     * @return
     */
    public Boolean checkJs(Long xsdId, String sfkIds) {
        try {
            Xsd xsdItem = this.xsdDao.get(xsdId);
            // 总货款
            double zhk = 0.0;
            for (Xsmx xsmx : xsdItem.getXsmxList()) {
                double sum = CalcUtils.mulDouble(xsmx.getHsj(), xsmx.getSbsl()).doubleValue();
                zhk += sum;
            }
            String[] sfkId = sfkIds.split(",");
            List<Sfk> sfkList = new ArrayList<Sfk>();
            for (int i = 0; i < sfkId.length; i++) {
                if (StringUtils.isNotBlank(sfkId[i])) {
                    Sfk sfk = this.skshDao.get(Long.valueOf(sfkId[i]));
                    sfkList.add(sfk);
                }
            }
            // 总挂款金额,去除代理费
            double gkje = 0.0;
            for (Sfk sfk : sfkList) {
                if (!sfk.getKxsy().getZ().equals("代理费用")) {
                    double sum = CalcUtils.round(sfk.getYe(), 4);
                    gkje += sum;
                }
            }

            if (CalcUtils.round(gkje, 2) >= CalcUtils.round(zhk, 2)) {
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {

        }
        return null;
    }


    /**
     * 计算当前代理费和贴息，先进行配款
     *
     * @param xsdItem
     * @param sfkIds
     */
    @Transactional
    public List<Map<Long, Double>> jsGk(Xsd xsdItem, String sfkIds) throws Exception {
        String[] sfkId = sfkIds.split(",");
        List<Sfk> sfkList = new ArrayList<Sfk>();
        List<Map<Long, Double>> mapList = new ArrayList<Map<Long, Double>>();
        double plusJe;
        for (int i = 0; i < sfkId.length; i++) {
            if (StringUtils.isNotBlank(sfkId[i])) {
                Map<Long, Double> map = new HashMap<Long, Double>();
                Sfk sfk = this.skshDao.get(Long.valueOf(sfkId[i]));
                sfkList.add(sfk);
                map.put(sfk.getId(), sfk.getYe());
                mapList.add(map);
            }
        }
        if (xsdItem.getXsht().getZddhcght().getLastsh() == 1) {//最后一次赎货
            List<Sfk> sfkListTemp = new ArrayList<Sfk>();
            for (Sfk sfk : sfkList) {
                if (sfk.getKxsy().getZ().equals("货款")) {
                    sfkListTemp.add(sfk);
                }
            }
            // 先用货款再用保证金
            for (Sfk sfk : sfkList) {
                if (sfk.getKxsy().getZ().equals("合同保证金")) {
                    sfkListTemp.add(sfk);
                }
            }
            xsdglupdateXsmxYe(xsdItem);
            plusJe = this.generalMethodToWithMoney2(xsdItem.getId(), sfkListTemp, false);
        } else {
            List<Sfk> sfkListTemp = new ArrayList<Sfk>();
            for (Sfk sfk : sfkList) {
                if (sfk.getKxsy().getZ().equals("货款")) {
                    sfkListTemp.add(sfk);
                }
            }
            xsdglupdateXsmxYe(xsdItem);
            plusJe = this.generalMethodToWithMoney2(xsdItem.getId(), sfkList, false);
        }
        if (plusJe > 0) {
            throw new RuntimeException("货款不足，差额约为：" + String.valueOf(plusJe));
        }
        return mapList;
    }

    /**
     * 计算当前代理费和贴息
     *
     * @param xsdItem
     * @throws Exception
     */
    @Transactional
    public synchronized List<Jfmx> executeDqTxAndDlf(Xsd xsdItem) {
        List<Jfmx> jfmxList = this.jfmxDao.findJfmxCalDLf(xsdItem.getId());
        if (null != jfmxList && jfmxList.size() > 0) {
            //执行存储过程计算代理费1
            for (Jfmx jfmx : jfmxList) {
                String result = this.xsdDao.executeDLF(jfmx.getXsht().getId(), jfmx.getXsmx().getId(), jfmx.getId(), xsdItem);
                jfmx.setKhfksj(result.split(",")[0]);
                jfmx.setTzfksj(result.split(",")[1]);
                jfmx.setSjzyts(Double.valueOf(result.split(",")[2]));
                jfmx.setJszyts(result.split(",")[3]);
                jfmx.setDlfje(Double.valueOf(result.split(",")[4]));
                jfmx.setHsj(Double.valueOf(result.split(",")[5]));
            }
        }
        return jfmxList;
    }

    /**
     * 操作数据
     *
     * @param xsdId
     */
    @Transactional
    public void dealDate(Long xsdId, List<Map<Long, Double>> listSfk) {
        if (listSfk != null && listSfk.size() > 0) {
            if (null != listSfk && listSfk.size() > 0) {
                for (Map<Long, Double> map : listSfk) {
                    for (Long key : map.keySet()) {
                        Sfk sfk = this.skshDao.get(key);
                        sfk.setYe(map.get(key));
                        this.skshDao.save(sfk);
                    }
                }
            }
            List<Jfmx> jfmxList = this.jfmxDao.findJfmxByXsdId(xsdId);
            for (Jfmx jfmx : jfmxList) {
                this.jfmxDao.delete(jfmx);
            }
        }
    }

//======================================挂款，产生计费明细start==============================================================

    /**
     * 通用方法
     *
     * @param xsdId
     * @param sfkList
     */
//    public void generalMethodToWithMoney(Long xsdId, List<Sfk> sfkList, Double zjzyf, Double dqtx) {
//        Xsd xsd = xsdDao.get(xsdId);
//        Double zsl = 0.0;
//        for (Xsmx xsmx : xsd.getXsmxList()) {
//            zsl += xsmx.getSbsl();
//        }
//
//        // 平均分资金占用费
//        Double pjzjfzyf = 0.0;
//        if (null != zjzyf && zjzyf.doubleValue() > 0) {
//            pjzjfzyf = zjzyf / zsl;
//        }
//
//        // 平均分贴息
//        Double pjdatx = 0.0;
//        if (null != dqtx && dqtx.doubleValue() > 0) {
//            pjdatx = dqtx / zsl;
//        }
//
//        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
//        String shsj = sf.format(new Date());
//        List<Xsmx> xsmxList = xsd.getXsmxList();
//        if (sfkList.size() > 0) {
//            Double temp;
//            a:
//            for (Xsmx xsmx : xsmxList) {
//                temp = xsmx.getXsmxYe();
//                Double syzl = xsmx.getSbsl();
//                if (temp > 0) {
//                    b:
//                    for (Sfk sfk : sfkList) {
//                        Sfk sfkTemp = this.skshDao.get(sfk.getId());
//                        if (sfkTemp.getYe() > 0) {
//                            if (temp == sfkTemp.getYe()) {
//                                Jfmx j = new Jfmx();
//                                j.setCreated_date(new Date());
//                                j.setKh(xsmx.getXsd().getKh());
//                                j.setXsd(xsd);
//                                j.setXsht(xsd.getXsht());
//                                j.setXsmx(xsmx);
//                                j.setSfk(sfkTemp);
//                                j.setZl(syzl);
//                                j.setHsj(CalcUtils.round(xsmx.getHsj(), 4));
//                                j.setSjjsj(CalcUtils.round(xsmx.getSjdj(), 4));
//                                j.setGhje(CalcUtils.round(temp, 2));
//                                j.setZjfpje(CalcUtils.round(temp, 2));
//                                j.setZjzyf(CalcUtils.round(j.getZl() * pjzjfzyf, 2));
//                                j.setTxje(CalcUtils.round(j.getZl() * pjdatx, 2));
//                                j.setShsj(shsj);
//                                jfmxDao.save(j);
//                                sfkTemp.setYe(0d);
//                                skshDao.save(sfkTemp);
//                                xsmx.setXsmxYe(0d);
//                                xsmx.setSjdj(xsmx.getHsj());
//                                xsmxDao.save(xsmx);
//                                break b;
//                            }
//                            if (temp < sfkTemp.getYe()) {
//                                Jfmx j = new Jfmx();
//                                j.setCreated_date(new Date());
//                                j.setKh(xsmx.getXsd().getKh());
//                                j.setXsd(xsd);
//                                j.setXsht(xsd.getXsht());
//                                j.setXsmx(xsmx);
//                                j.setSfk(sfkTemp);
//                                j.setZl(CalcUtils.round(temp / xsmx.getHsj(), 6));
//                                j.setHsj(CalcUtils.round(xsmx.getHsj(), 4));
//                                j.setSjjsj(CalcUtils.round(xsmx.getHsj(), 4));
//                                j.setGhje(CalcUtils.round(temp, 2));
//                                j.setZjfpje(CalcUtils.round(temp, 2));
//                                j.setZjzyf(CalcUtils.round(j.getZl() * pjzjfzyf, 2));
//                                j.setTxje(CalcUtils.round(j.getZl() * pjdatx, 2));
//                                j.setShsj(shsj);
//                                jfmxDao.save(j);
//                                sfkTemp.setYe(CalcUtils.round(sfkTemp.getYe() - temp, 2));
//                                skshDao.save(sfkTemp);
//                                xsmx.setXsmxYe(0d);
//                                xsmx.setSjdj(xsmx.getHsj());
//                                xsmxDao.save(xsmx);
//                                break b;
//                            }
//                            if (temp > sfkTemp.getYe()) {
//                                Jfmx j = new Jfmx();
//                                j.setCreated_date(new Date());
//                                j.setKh(xsmx.getXsd().getKh());
//                                j.setXsd(xsd);
//                                j.setXsht(xsd.getXsht());
//                                j.setXsmx(xsmx);
//                                j.setSfk(sfkTemp);
//                                syzl = CalcUtils.round(xsmx.getSbsl() - sfkTemp.getYe() / xsmx.getHsj(), 6);
//                                j.setZl(CalcUtils.round(sfkTemp.getYe() / xsmx.getHsj(), 6));
//                                j.setHsj(CalcUtils.round(xsmx.getHsj(), 4));
//                                j.setSjjsj(CalcUtils.round(xsmx.getHsj(), 4));
//                                j.setGhje(CalcUtils.round(sfkTemp.getYe(), 2));
//                                j.setZjfpje(CalcUtils.round(sfkTemp.getYe(), 2));
//                                j.setZjzyf(CalcUtils.round(j.getZl() * pjzjfzyf, 2));
//                                j.setTxje(CalcUtils.round(j.getZl() * pjdatx, 2));
//                                j.setShsj(shsj);
//                                jfmxDao.save(j);
//                                temp = CalcUtils.round(temp - sfkTemp.getYe(), 2);
//                                sfkTemp.setYe(0d);
//                                skshDao.save(sfkTemp);
//                                xsmx.setXsmxYe(temp);
//                                xsmx.setSjdj(xsmx.getHsj());
//                                xsmxDao.save(xsmx);
//                            }
//                        }
//                    }
//                }
//            }
//        }
//    }

    /**
     * 通用方法2
     *
     * @param xsdId
     * @param sfkList
     */
    public double generalMethodToWithMoney2(Long xsdId, List<Sfk> sfkList, Boolean bool) throws Exception {
        Xsd xsd = xsdDao.get(xsdId);
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        String shsj = sf.format(new Date());
        List<Xsmx> xsmxList = xsd.getXsmxList();
        double plusJe = 0.0;
        if (sfkList.size() > 0) {
            Double temp;
            a:
            for (Xsmx xsmx : xsmxList) {
                temp = xsmx.getXsmxYe();
                if (temp > 0) {
                    b:
                    for (Sfk sfk : sfkList) {
                        Sfk sfkTemp = this.skshDao.get(sfk.getId());
                        if (sfkTemp.getFkfs().getZ().equals("承兑")) {
                            Map map = this.executiveTx(xsd, sfkTemp);
                            Double ye = sfkTemp.getYe() - Double.valueOf(map.get("tx").toString());
                            if (sfkTemp.getYe() > 0) {
                                if (temp <= ye) {
                                    Jfmx j = new Jfmx();
                                    j.setCreated_date(new Date());
                                    j.setCreateUser(YgService.getCurrentYg());
                                    j.setKh(xsmx.getXsd().getKh());
                                    j.setXsd(xsd);
                                    j.setXsht(xsd.getXsht());
                                    j.setXsmx(xsmx);
                                    j.setSfk(sfkTemp);
                                    j.setZl(CalcUtils.round(temp / xsmx.getHsj(), 6));
                                    j.setHsj(CalcUtils.round(xsmx.getHsj(), 4));
                                    j.setSjjsj(CalcUtils.round(xsmx.getHsj(), 4));
                                    j.setGhje(CalcUtils.round(temp, 2));
                                    j.setZjfpje(CalcUtils.round(temp, 2));
                                    j.setTxts(Double.valueOf(map.get("actualDay").toString()));
                                    j.setShsj(shsj);
                                    j.setSffkdlf(0);
                                    j.setYhje(0D);
                                    jfmxDao.save(j);
                                    double tx = (temp / ye) * Double.valueOf(map.get("tx").toString());
                                    j.setTxje(CalcUtils.round(tx, 2));
                                    sfkTemp.setYe(CalcUtils.round(sfkTemp.getYe() - temp - tx, 2));
                                    skshDao.save(sfkTemp);
                                    xsmx.setXsmxYe(0d);
//                                    xsmx.setSjdj(xsmx.getHsj());
                                    xsmxDao.save(xsmx);
                                    temp = 0.0;
                                    break b;
                                }
                                if (temp > ye) {
                                    Jfmx j = new Jfmx();
                                    j.setCreated_date(new Date());
                                    j.setCreateUser(YgService.getCurrentYg());
                                    j.setKh(xsmx.getXsd().getKh());
                                    j.setXsd(xsd);
                                    j.setXsht(xsd.getXsht());
                                    j.setXsmx(xsmx);
                                    j.setSfk(sfkTemp);
                                    j.setZl(CalcUtils.round(sfkTemp.getYe() / xsmx.getHsj(), 6));
                                    j.setHsj(CalcUtils.round(xsmx.getHsj(), 4));
                                    j.setSjjsj(CalcUtils.round(xsmx.getHsj(), 4));
                                    j.setGhje(CalcUtils.round(sfkTemp.getYe(), 2));
                                    j.setZjfpje(CalcUtils.round(sfkTemp.getYe(), 2));
                                    j.setTxts(Double.valueOf(map.get("actualDay").toString()));
                                    j.setTxje(CalcUtils.round(Double.valueOf(map.get("tx").toString()), 2));
                                    j.setShsj(shsj);
                                    j.setSffkdlf(0);
                                    j.setYhje(0D);
                                    jfmxDao.save(j);
                                    temp = CalcUtils.round(temp - ye, 2);
                                    sfkTemp.setYe(0d);
                                    skshDao.save(sfkTemp);
                                    xsmx.setXsmxYe(temp);
//                                    xsmx.setSjdj(xsmx.getHsj());
                                    xsmxDao.save(xsmx);
                                }
                            }
                        } else if (sfkTemp.getFkfs().getZ().equals("现汇")) {
                            if (sfkTemp.getKxsy().getZ().equals("合同保证金")) {
                                Double ye = sfkTemp.getYe();
                                if (sfkTemp.getYe() > 0) {
                                    if (temp <= ye) {
                                        Jfmx j = new Jfmx();
                                        j.setCreated_date(new Date());
                                        j.setCreateUser(YgService.getCurrentYg());
                                        j.setKh(xsmx.getXsd().getKh());
                                        j.setXsd(xsd);
                                        j.setXsht(xsd.getXsht());
                                        j.setXsmx(xsmx);
                                        j.setSfk(sfkTemp);
                                        j.setZl(CalcUtils.round(temp / xsmx.getHsj(), 6));
                                        j.setHsj(CalcUtils.round(xsmx.getHsj(), 4));
                                        j.setSjjsj(CalcUtils.round(xsmx.getHsj(), 4));
                                        j.setGhje(CalcUtils.round(temp, 2));
                                        j.setZjfpje(CalcUtils.round(temp, 2));
                                        j.setTxts(0d);
                                        j.setTxje(0d);
                                        j.setShsj(shsj);
                                        j.setYhje(0d);
                                        j.setSffkdlf(0);
                                        jfmxDao.save(j);
                                        sfkTemp.setYe(CalcUtils.round(sfkTemp.getYe() - temp, 2));
                                        skshDao.save(sfkTemp);
                                        xsmx.setXsmxYe(0d);
//                                        xsmx.setSjdj(xsmx.getHsj());
                                        xsmxDao.save(xsmx);
                                        temp = 0.0;
                                        break b;
                                    }
                                    if (temp > ye) {
                                        Jfmx j = new Jfmx();
                                        j.setCreated_date(new Date());
                                        j.setCreateUser(YgService.getCurrentYg());
                                        j.setKh(xsmx.getXsd().getKh());
                                        j.setXsd(xsd);
                                        j.setXsht(xsd.getXsht());
                                        j.setXsmx(xsmx);
                                        j.setSfk(sfkTemp);
                                        j.setZl(CalcUtils.round(sfkTemp.getYe() / xsmx.getHsj(), 6));
                                        j.setHsj(CalcUtils.round(xsmx.getHsj(), 4));
                                        j.setSjjsj(CalcUtils.round(xsmx.getHsj(), 4));
                                        j.setGhje(CalcUtils.round(sfkTemp.getYe(), 2));
                                        j.setZjfpje(CalcUtils.round(sfkTemp.getYe(), 2));
                                        j.setTxts(0d);
                                        j.setTxje(0d);
                                        j.setShsj(shsj);
                                        j.setYhje(0d);
                                        j.setSffkdlf(0);
                                        jfmxDao.save(j);
                                        temp = CalcUtils.round(temp - ye, 2);
                                        sfkTemp.setYe(0d);
                                        skshDao.save(sfkTemp);
                                        xsmx.setXsmxYe(temp);
//                                        xsmx.setSjdj(xsmx.getHsj());
                                        xsmxDao.save(xsmx);
                                    }
                                }
                            } else {
                                Cght cght = xsd.getXsht().getZddhcght();
                                Double yhbl = cght.getYhbl() * 0.01;
                                Double yhje = sfkTemp.getYe() * yhbl;
                                Double ye = sfkTemp.getYe() + CalcUtils.round(yhje, 2);
                                if (sfkTemp.getYe() > 0) {
                                    if (temp <= ye) {
                                        Jfmx j = new Jfmx();
                                        j.setCreated_date(new Date());
                                        j.setCreateUser(YgService.getCurrentYg());
                                        j.setKh(xsmx.getXsd().getKh());
                                        j.setXsd(xsd);
                                        j.setXsht(xsd.getXsht());
                                        j.setXsmx(xsmx);
                                        j.setSfk(sfkTemp);
                                        j.setZl(CalcUtils.round(temp / xsmx.getHsj(), 6));
                                        j.setHsj(CalcUtils.round(xsmx.getHsj(), 4));
                                        j.setSjjsj(CalcUtils.round(xsmx.getHsj(), 4));
                                        j.setGhje(CalcUtils.round(temp, 2));
                                        j.setZjfpje(CalcUtils.round(temp / (1 + yhbl), 2));
                                        j.setTxts(0d);
                                        j.setTxje(0d);
                                        j.setShsj(shsj);
                                        j.setYhje(CalcUtils.round((temp / (1 + yhbl) * yhbl), 2));
                                        j.setSffkdlf(0);
                                        jfmxDao.save(j);
                                        sfkTemp.setYe(CalcUtils.round(sfkTemp.getYe() - temp / (1 + yhbl), 2));
                                        skshDao.save(sfkTemp);
                                        xsmx.setXsmxYe(0d);
//                                        xsmx.setSjdj(xsmx.getHsj());
                                        xsmxDao.save(xsmx);
                                        temp = 0.0;
                                        break b;
                                    }
                                    if (temp > ye) {
                                        Jfmx j = new Jfmx();
                                        j.setCreated_date(new Date());
                                        j.setCreateUser(YgService.getCurrentYg());
                                        j.setKh(xsmx.getXsd().getKh());
                                        j.setXsd(xsd);
                                        j.setXsht(xsd.getXsht());
                                        j.setXsmx(xsmx);
                                        j.setSfk(sfkTemp);
                                        j.setZl(CalcUtils.round(ye / xsmx.getHsj(), 6));
                                        j.setHsj(CalcUtils.round(xsmx.getHsj(), 4));
                                        j.setSjjsj(CalcUtils.round(xsmx.getHsj(), 4));
                                        j.setGhje(CalcUtils.round(ye, 2));
                                        j.setZjfpje(CalcUtils.round(sfk.getYe(), 2));
                                        j.setTxts(0d);
                                        j.setTxje(0d);
                                        j.setShsj(shsj);
                                        j.setYhje(CalcUtils.round(yhje, 2));
                                        j.setSffkdlf(0);
                                        jfmxDao.save(j);
                                        temp = CalcUtils.round(temp - ye, 2);
                                        sfkTemp.setYe(0d);
                                        skshDao.save(sfkTemp);
                                        xsmx.setXsmxYe(temp);
//                                        xsmx.setSjdj(xsmx.getHsj());
                                        xsmxDao.save(xsmx);
                                    }
                                }
                            }
                        }
                    }
                    plusJe += temp;
                }
            }
        }
        if (plusJe <= 0 && bool) {
            this.executeDqTxAndDlf(this.xsdDao.get(xsdId));
        }
        return plusJe;
    }

    /**
     * 填充销售明细余额
     *
     * @param xsd
     * @return
     * @throws Exception
     */
    public void xsdglupdateXsmxYe(Xsd xsd) {
        for (Xsmx xsmx : xsd.getXsmxList()) {
            xsmx.setXsmxYe(CalcUtils.mulDouble(xsmx.getSbsl(), xsmx.getHsj()));
            xsmxDao.save(xsmx);
        }
    }
//=========================================挂款，产生计费明细end===========================================================

//===================================一次性释放保证金start=================================================================

    /**
     * 先保存收付款信息
     *
     * @param xsd
     * @return
     */
    public List<Sfk> getGkSfk(Xsd xsd) {
        List<Sfk> sfkList = new ArrayList<Sfk>();
        for (Sfk sfk : xsd.getSkList()) {
            Sfk skf = this.skshDao.get(sfk.getId());
            sfkList.add(skf);
        }
        return sfkList;
    }


    /**
     * 先保存收付款信息，失败后进行处理
     *
     * @param xsd
     * @return
     */
    public List<Map<Long, Double>> copyGkSfk(Xsd xsd) {
        List<Map<Long, Double>> sfkList = new ArrayList<Map<Long, Double>>();
        for (Sfk sfk : xsd.getSkList()) {
            Map map = new HashMap();
            Sfk tempSfk = this.skshDao.get(sfk.getId());
            map.put(sfk.getId(), tempSfk.getYe());
            sfkList.add(map);
        }
        return sfkList;
    }

    /**
     * 挂款同时进行配款
     * （先现金后承兑，先到先用）
     *
     * @param xsdItem
     * @param sfkList
     * @throws Exception
     */
    @Transactional
    public String gkOnetimeBond(Xsd xsdItem, List<Sfk> sfkList) throws Exception {
        List<Jfmx> jfmxList = this.jfmxDao.findJfmxByXsdId(xsdItem.getId());
        // 判断是否已经挂款
        if (null != jfmxList && jfmxList.size() > 0) {
            throw new RuntimeException("不能重复挂款！");
        } else {
            Double plusJe;
            if (xsdItem.getXsht().getZddhcght().getLastsh() == 1) {
                // 先用货款，后用保证金
                List<Sfk> sfkListTemp = new ArrayList<Sfk>();
                for (Sfk sfk : sfkList) {
                    if (sfk.getKxsy().getZ().equals("货款")) {
                        sfkListTemp.add(sfk);
                    }
                }
                // 先用货款再用保证金
                for (Sfk sfk : sfkList) {
                    if (sfk.getKxsy().getZ().equals("合同保证金")) {
                        sfkListTemp.add(sfk);
                    }
                }
                xsdglupdateXsmxYe(xsdItem);
                plusJe = this.generalMethodToWithMoney2(xsdItem.getId(), sfkListTemp, true);
                if (plusJe > 0) {
                    throw new RuntimeException("货款和保证金不足，差额约为：" + String.valueOf(plusJe));
                } else {
                    this.executeDqTxAndDlf(xsdItem);
                }
            } else {
                List<Sfk> sfkListTemp = new ArrayList<Sfk>();
                for (Sfk sfk : sfkList) {
                    if (sfk.getKxsy().getZ().equals("货款")) {
                        sfkListTemp.add(sfk);
                    }
                }
                xsdglupdateXsmxYe(xsdItem);
                plusJe = this.generalMethodToWithMoney2(xsdItem.getId(), sfkListTemp, true);
                if (plusJe > 0) {
                    throw new RuntimeException("货款不足，差额约为：" + String.valueOf(plusJe));
                } else {
                    this.executeDqTxAndDlf(xsdItem);
                }
            }
        }
        return "0";
    }

    /**
     * 处理代理费情况
     *
     * @param xsdItem
     * @param sfkList
     * @param xsdMap
     * @param bzjsfdlf
     * @param sfkzdlf
     * @return
     */
    @Transactional
    public void dealDlfInfo(Xsd xsdItem, List<Sfk> sfkList, List<Map<Long, Double>> xsdMap, Boolean bzjsfdlf, Boolean sfkzdlf) {
        Double plusDlf = 0.0;
        List<Sfk> skfTemp = new ArrayList();
        for (Sfk sfk : sfkList) {
            if (sfk.getKxsy().getZ().equals("代理费用")) {
                skfTemp.add(sfk);
            }
        }

        // 最后一次赎货，并且保证金充当代理费
        if (bzjsfdlf) {
            for (Sfk sfk : sfkList) {
                if (sfk.getKxsy().getZ().equals("合同保证金")) {
                    skfTemp.add(sfk);
                }
            }
        }
        // 查询要付款的代理费
        List<Jfmx> jfmxListTemp = null;
        if (xsdItem.getXsht().getZddhcght().getLastsh() == 1) {
            jfmxListTemp = this.jfmxDao.findJfmxByXshtIdXsdId(xsdItem, true);
        } else {
            if (sfkzdlf) {
                jfmxListTemp = this.jfmxDao.findJfmxByXshtIdXsdId(xsdItem, false);
            }
        }
        if (null != jfmxListTemp && jfmxListTemp.size() > 0) {
            for (Jfmx jfmx : jfmxListTemp) {
                Double temp = jfmx.getDlfje();
                for (Sfk sfk : skfTemp) {
                    Dlf dlf = new Dlf();
                    if (temp < sfk.getYe()) {
                        sfk.setYe(CalcUtils.round(sfk.getYe() - temp, 2));
                        temp = 0.0;
                        dlf.setJfmx(jfmx);
                        dlf.setSfkId(sfk.getId());
                        dlf.setXsd(xsdItem);
                        dlf.setDlf(Float.valueOf(jfmx.getDlfje().toString()));
                        dlf.setCreated_date(new Date());
                        this.dlfDao.save(dlf);
                        break;
                    } else {
                        temp -= sfk.getYe();
                        sfk.setYe(0.0);
                        dlf.setJfmx(jfmx);
                        dlf.setSfkId(sfk.getId());
                        dlf.setXsd(xsdItem);
                        dlf.setDlf(Float.valueOf(sfk.getYe().toString()));
                        dlf.setCreated_date(new Date());
                        this.dlfDao.save(dlf);
                    }
                }
                jfmx.setSffkdlf(1);
                this.jfmxDao.save(jfmx);
                plusDlf += temp;
            }
        }
        // 判断代理费是否满足
        if (plusDlf > 0) {
            dealDate(xsdItem.getId(), xsdMap);
            throw new RuntimeException("代理费不足，差额约:" + String.valueOf(CalcUtils.round(plusDlf, 2)));
        } else {
            xsdItem.setZt("ygk");
            xsdItem.setLastUpdated(new Date());
            xsdDao.save(xsdItem);
        }
    }

    /**
     * 计算贴息
     *
     * @param xsd
     * @return
     */
    //todo
    private Map<String, String> executiveTx(Xsd xsd, Sfk sfk) {
        Map<String, String> map = new HashMap<String, String>();
        Integer mxtx = xsd.getXsht().getZddhcght().getMxts();
        // 日贴息率
        Double txl = xsd.getXsht().getZddhcght().getTxl() / 100 / 30;
        // 承兑到期时间
        Date cddqsj = sfk.getEndDate();
        // 客户付款时间
        Date khfksj = sfk.getKhfksj();
        // 占用天数
        Long paymentDay = (cddqsj.getTime() - khfksj.getTime()) / (24 * 60 * 60 * 1000);
        // 实际占用天数
        Long actualDay = paymentDay - mxtx;
        if (actualDay < 0) {
            actualDay = 0l;
        }
        map.put("actualDay", actualDay.toString());
        Double tx = CalcUtils.round(sfk.getYe() * actualDay * txl, 2);
        map.put("tx", tx.toString());
        return map;
    }

    /**
     * 根据实际的传入价格算贴息
     *
     * @param xsd
     * @param sfk
     * @param sjje
     * @return
     */
    private Map<String, String> executiveTx2(Xsd xsd, Sfk sfk, Double sjje) {
        Map<String, String> map = new HashMap<String, String>();
        Integer mxtx = xsd.getXsht().getZddhcght().getMxts();
        // 日贴息率
        Double txl = xsd.getXsht().getZddhcght().getTxl() / 100 / 30;
        // 承兑到期时间
        Date cddqsj = sfk.getEndDate();
        // 客户付款时间
        Date khfksj = sfk.getKhfksj();
        // 占用天数
        Long paymentDay = (cddqsj.getTime() - khfksj.getTime()) / (24 * 60 * 60 * 1000);
        // 实际占用天数
        Long actualDay = paymentDay - mxtx;
        if (actualDay < 0) {
            actualDay = 0l;
        }
        map.put("actualDay", actualDay.toString());
        Double tx = CalcUtils.round(sjje * actualDay * txl, 2);
        map.put("tx", tx.toString());
        return map;
    }

    /**
     * 配款
     *
     * @param xsdItem
     * @throws Exception
     */
    @Transactional
    public synchronized void oneTimeAllocatePay(Xsd xsdItem) throws Exception {
        Xsd xsd = xsdDao.get(xsdItem.getId());
        boolean bool = true;
        // 调用接口。在线赎货-》居中结算，并且是第三方公司仓储和Excel挂单不调用接口
        if (null != xsd.getXsht().getSfjs() && xsd.getXsht().getSfjs().equals("1")) {
            Gson gson = new Gson();
            String json = dealObjectToJson(xsd);
            String result = this.webserviceTransService.putContractWebServiceArgs(json);
            List<Map<String, Object>> list = gson.fromJson(result, new TypeToken<List<Map<String, Object>>>() {
            }.getType());
            if (null != list && list.size() > 0) {
                String code = list.get(0).get("code").toString();
                String msg = list.get(0).get("message").toString();
                if (!code.equals("0")) {
                    throw new RuntimeException(msg);
                }
            } else {
                throw new RuntimeException("配款失败!");
            }
        }
        if (bool) {
            dealRetreatMoreBackSfk(xsd);
            xsd.setZt("ypk");
            xsdDao.save(xsd);
            // 把锁定的保证金收款状态改成“ytz”
            List<Sfk> bzjSfkList = skshDao.findBzjsWithOutLocks(xsd.getXsht().getId());
            if (null != bzjSfkList && bzjSfkList.size() > 0) {
                for (Sfk sfk : bzjSfkList) {
                    if (sfk.getZt().equals("yjs")) {
                        sfk.setZt("ytz");
                        skshDao.save(sfk);
                    }
                }
            }
        }
    }

    /**
     * 处理一次性配款后定价收款多勾少补
     *
     * @param xsdItem
     */
    @Transactional
    public synchronized void dealRetreatMoreBackSfk(Xsd xsdItem) {
        Cght cght = cghtDao.get(xsdItem.getXsht().getZddhcght().getId());
        Boolean bool1 = cght.getSfhdj();//判断是否后定价
        if (bool1 != null && bool1) {
            List<Map> listMap = this.jfmxDao.GroupBySfkFromJfmx(xsdItem.getId());
            if (listMap != null && listMap.size() > 0) {
                for (Map map : listMap) {
                    Sfk sk = skshDao.get(Long.valueOf(map.get("id").toString()));
                    if (sk.getFkfs().getZ().equals("现汇")) {
                        //要把现金优惠+资金分配金额加回去
                        sk.setYe(sk.getYe() + Double.valueOf(map.get("zjfpje").toString()));
                        skshDao.save(sk);
                    } else if (sk.getFkfs().getZ().equals("承兑")) {
                        //要考虑把贴息+资金分配金额加回去
                        sk.setYe(sk.getYe() + Double.valueOf(map.get("zjfpje").toString()) + Double.valueOf(map.get("txje").toString()));
                        skshDao.save(sk);
                    }
                }
            }
            List<Jfmx> jfmxList = this.jfmxDao.findJfmxByXsdId(xsdItem.getId());
            if (null != jfmxList && jfmxList.size() > 0) {
                for (Jfmx jfmx : jfmxList) {
                    Sfk sk = skshDao.get(jfmx.getSfk().getId());
                    Double sjdj = xsmxDao.get(jfmx.getXsmx().getId()).getSjdj();
                    if (sk.getFkfs().getZ().equals("现汇")) {
                        //要把现金优惠加回去
                        Double shje = sjdj * jfmx.getZl();
                        Double zjfpje = shje / (1 + cght.getYhbl() * 0.01);
                        Double yhje = zjfpje * cght.getYhbl() * 0.01;
                        sk.setYe(sk.getYe() - zjfpje);
                        skshDao.save(sk);
                        jfmx.setZjfpje(CalcUtils.round(zjfpje, 2));
                        jfmx.setYhje(CalcUtils.round(yhje, 2));
                        jfmxDao.save(jfmx);
                    } else if (sk.getFkfs().getZ().equals("承兑")) {
                        //要考虑把贴息加回去
                        Double shje = sjdj * jfmx.getZl();
                        Map map1 = executiveTx(xsdItem, sk);
                        Double txje = (shje / sk.getYe()) * Double.valueOf(map1.get("tx").toString());
                        jfmx.setZjfpje(CalcUtils.round(shje + txje, 2));
                        jfmx.setTxje(CalcUtils.round(txje, 2));
                        jfmxDao.save(jfmx);
                        sk.setYe(sk.getYe() - shje - txje);
                        skshDao.save(sk);
                    }
                }
            }
        }
    }

    /**
     * 处理线上赎货报文
     *
     * @param xsd
     * @return
     */
    private String dealObjectToJson(Xsd xsd) {
        StringBuffer sb = new StringBuffer();
        String str;
        SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        Jydd jydd = this.jyddDao.findUniqueByProperty("order_id", xsd.getOrderId());
        if (null == jydd) {
            throw new RuntimeException("配款失败!");
        }
        sb.append("[");
        Double totalJe = 0.0;
        Double totalZl = 0.0;
        for (Xsmx xsmx : xsd.getXsmxList()) {
            Goodses goodses = this.goodsesDao.findGoodses(jydd.getId(), xsmx.getBindNo());
            if (null == goodses) {
                throw new RuntimeException("配款失败!");
            }
            Double sumJe = 0.0;
            Double dlfy = 0.0;
            for (Jfmx jfmx : xsmx.getJfmxList()) {
                Double dlfje = jfmx.getDlfje() == null ? 0 : jfmx.getDlfje();
                Double txje = jfmx.getTxje() == null ? 0 : jfmx.getTxje();
                Double zjzyf = jfmx.getZjzyf() == null ? 0 : jfmx.getZjzyf();
                dlfy += dlfje + txje + zjzyf;
                sumJe += jfmx.getGhje() + dlfy;
            }
            // 总金额和总重量
            totalJe += sumJe;
            totalZl += Double.valueOf(goodses.getMeasure());
        }

        for (Xsmx xsmx : xsd.getXsmxList()) {
            Double dlfy = 0.0;
            Double realPrice;
            Double sumJe = 0.0;
            Goodses goodses = this.goodsesDao.findGoodses(jydd.getId(), xsmx.getBindNo());
            for (Jfmx jfmx : xsmx.getJfmxList()) {
                Double dlfje = jfmx.getDlfje() == null ? 0 : jfmx.getDlfje();
                Double txje = jfmx.getTxje() == null ? 0 : jfmx.getTxje();
                Double zjzyf = jfmx.getZjzyf() == null ? 0 : jfmx.getZjzyf();
                dlfy += dlfje + txje + zjzyf;
                sumJe += jfmx.getGhje() + dlfy;
            }
            realPrice = CalcUtils.round(sumJe / Double.valueOf(goodses.getMeasure()), 2);
            sb.append("{");
            sb.append("\"").append("order_id").append("\":").append("\"").append(xsd.getOrderId()).append("\"").append(",");
            sb.append("\"").append("order_sn").append("\":").append("\"").append(jydd.getOrder_sn()).append("\"").append(",");
            sb.append("\"").append("operator").append("\":").append("\"").append(jydd.getOperator()).append("\"").append(",");
            sb.append("\"").append("seller_name").append("\":").append("\"").append(jydd.getSeller_name()).append("\"").append(",");
            sb.append("\"").append("memberCode").append("\":").append("\"").append(jydd.getMemberCode()).append("\"").append(",");
            sb.append("\"").append("buyer_id").append("\":").append("\"").append(jydd.getBuyer_id()).append("\"").append(",");
            sb.append("\"").append("buyer_name").append("\":").append("\"").append(jydd.getBuyer_name()).append("\"").append(",");
            sb.append("\"").append("buyer_email").append("\":").append("\"").append(jydd.getBuyer_email()).append("\"").append(",");
            sb.append("\"").append("buyer_account").append("\":").append("\"").append(Tools.NullToString(jydd.getBuyer_account())).append("\"").append(",");
            sb.append("\"").append("status").append("\":").append("\"").append("20").append("\"").append(",");
            sb.append("\"").append("add_time").append("\":").append("\"").append(ft.format(xsd.getDateCreated())).append("\"").append(",");
            sb.append("\"").append("payment_name").append("\":").append("\"").append(Tools.NullToString(jydd.getPayment_bank())).append("\"").append(",");
            sb.append("\"").append("payment_code").append("\":").append("\"").append(Tools.NullToString(jydd.getPayment_code())).append("\"").append(",");
            sb.append("\"").append("payment_bankof").append("\":").append("\"").append(Tools.NullToString(jydd.getPayment_bankof())).append("\"").append(",");
            sb.append("\"").append("out_trade_sn").append("\":").append("\"").append(Tools.NullToString(jydd.getOut_trade_sn())).append("\"").append(",");
            sb.append("\"").append("pay_time").append("\":").append("\"").append(Tools.NullToString(jydd.getOut_trade_sn())).append("\"").append(",");
            sb.append("\"").append("pay_message").append("\":").append("\"").append(Tools.NullToString(jydd.getPay_message())).append("\"").append(",");
            sb.append("\"").append("ship_time").append("\":").append("\"").append(Tools.NullToString(Tools.NullToString(jydd.getShip_time()))).append("\"").append(",");
            sb.append("\"").append("express_company").append("\":").append("\"").append(Tools.NullToString(jydd.getExpress_company())).append("\"").append(",");
            sb.append("\"").append("finished_time").append("\":").append("\"").append(Tools.NullToString(jydd.getFinished_time())).append("\"").append(",");
            sb.append("\"").append("goods_amount").append("\":").append("\"").append(CalcUtils.round(totalJe, 2)).append("\"").append(",");
            sb.append("\"").append("goods_je").append("\":").append("\"").append(CalcUtils.round(sumJe, 2)).append("\"").append(",");
            sb.append("\"").append("discount").append("\":").append("\"").append(Tools.NullToString(jydd.getDiscount())).append("\"").append(",");
            sb.append("\"").append("expire_time").append("\":").append("\"").append(Tools.NullToString(jydd.getExpire_time())).append("\"").append(",");
            sb.append("\"").append("canceled_type").append("\":").append("\"").append(Tools.NullToString(jydd.getCanceled_type())).append("\"").append(",");
            sb.append("\"").append("payment_type").append("\":").append("\"").append(Tools.NullToString(jydd.getPayment_type())).append("\"").append(",");
            sb.append("\"").append("payment_type").append("\":").append("\"").append(Tools.NullToString(jydd.getPayment_type())).append("\"").append(",");
            sb.append("\"").append("shipped_type").append("\":").append("\"").append(Tools.NullToString(jydd.getShipped_type())).append("\"").append(",");
            sb.append("\"").append("payment_bank").append("\":").append("\"").append(Tools.NullToString(jydd.getPayment_bank())).append("\"").append(",");
            sb.append("\"").append("release_cargo_num").append("\":").append("\"").append(Tools.NullToString(jydd.getRelease_cargo_num())).append("\"").append(",");
            sb.append("\"").append("press_invoice").append("\":").append("\"").append(Tools.NullToString(jydd.getPress_invoice())).append("\"").append(",");
            sb.append("\"").append("notice_invoice").append("\":").append("\"").append(Tools.NullToString(jydd.getNotice_invoice())).append("\"").append(",");
            sb.append("\"").append("pay_order_status").append("\":").append("\"").append(Tools.NullToString(jydd.getPay_order_status())).append("\"").append(",");
            sb.append("\"").append("payment_id").append("\":").append("\"").append(Tools.NullToString(jydd.getPayment_id())).append("\"").append(",");
            sb.append("\"").append("is_use_balance").append("\":").append("\"").append(Tools.NullToString(jydd.getIs_use_balance())).append("\"").append(",");
            sb.append("\"").append("amount_of_balance").append("\":").append("\"").append(Tools.NullToString(jydd.getAmount_of_balance())).append("\"").append(",");
            sb.append("\"").append("package_SubItem").append("\":").append("\"").append(Tools.NullToString(jydd.getPackage_SubItem())).append("\"").append(",");
            sb.append("\"").append("is_online_payment").append("\":").append("\"").append(Tools.NullToString(jydd.getIs_online_payment())).append("\"").append(",");
            sb.append("\"").append("isCompetiveResource").append("\":").append("\"").append(0).append("\"").append(",");
            sb.append("\"").append("sellType").append("\":").append("\"").append(Tools.NullToString(jydd.getSellType())).append("\"").append(",");
            sb.append("\"").append("order_type").append("\":").append("\"").append(Tools.NullToString(jydd.getOrder_type())).append("\"").append(",");
            sb.append("\"").append("goodses").append("\":").append("[").append("{");
            sb.append("\"").append("spec_id").append("\":").append("\"").append(goodses.getSpec_id()).append("\"").append(",");
            sb.append("\"").append("goods_name").append("\":").append("\"").append(goodses.getGoods_name()).append("\"").append(",");
            sb.append("\"").append("price").append("\":").append("\"").append(realPrice).append("\"").append(",");
            sb.append("\"").append("real_price").append("\":").append("\"").append(realPrice).append("\"").append(",");
            sb.append("\"").append("quantity").append("\":").append("\"").append(goodses.getQuantity()).append("\"").append(",");
            sb.append("\"").append("measure").append("\":").append("\"").append(totalZl).append("\"").append(",");
            sb.append("\"").append("goodses_weight").append("\":").append("\"").append(goodses.getMeasure()).append("\"").append(",");
            sb.append("\"").append("outofstock").append("\":").append("\"").append(Tools.NullToString(goodses.getOutofstock())).append("\"").append(",");
            sb.append("\"").append("comment").append("\":").append("\"").append(Tools.NullToString(goodses.getComment())).append("\"").append(",");
            sb.append("\"").append("brand").append("\":").append("\"").append(goodses.getBrand()).append("\"").append(",");
            sb.append("\"").append("resource_serial_number").append("\":").append("\"").append(Tools.NullToString(goodses.getResource_serial_number())).append("\"").append(",");
            sb.append("\"").append("resource_serial_number_1").append("\":").append("\"").append(goodses.getResource_serial_number_1()).append("\"").append(",");
            sb.append("\"").append("purchase_contract_no").append("\":").append("\"").append(Tools.NullToString(goodses.getPurchase_contract_no())).append("\"").append(",");
            sb.append("\"").append("production_contract_no").append("\":").append("\"").append(Tools.NullToString(goodses.getProduction_contract_no())).append("\"").append(",");
            sb.append("\"").append("factoryId").append("\":").append("\"").append(Tools.NullToString(goodses.getFactory_id())).append("\"").append(",");
            sb.append("\"").append("pc").append("\":").append("\"").append(Tools.NullToString(goodses.getPc())).append("\"").append(",");
            sb.append("\"").append("spec").append("\":").append("\"").append(goodses.getSpec()).append("\"").append(",");
            sb.append("\"").append("metarial").append("\":").append("\"").append(Tools.NullToString(goodses.getMetarial())).append("\"").append(",");
            sb.append("\"").append("warehouse_name").append("\":").append("\"").append(Tools.NullToString(goodses.getWarehouse_name())).append("\"").append(",");
            sb.append("\"").append("region_name").append("\":").append("\"").append(Tools.NullToString(goodses.getRegion_name())).append("\"").append(",");
            sb.append("\"").append("user_id").append("\":").append("\"").append(Tools.NullToString(goodses.getUser_id())).append("\"");
            sb.append("}]},");
        }
        str = sb.substring(0, sb.length() - 1);
        str += "]";
        return str;
    }

//===================================一次性释放保证金end===================================================================


//===================================按比例释放保证金start=================================================================

    /**
     * 判断是否满足放货条件，并锁定货款，进行挂款操作
     *
     * @param xsdItem
     * @param xsd
     * @return
     */
    @Transactional
    public synchronized String gkProRataBond(Xsd xsdItem, Xsd xsd) {
        String result;
        Ablbzjgk ablbzjgk = this.ablbzjshDao.findAblbzjgk(xsdItem);
        if (null != ablbzjgk) {
            result = "success";
            xsdItem.setZt("ygk");
            xsdItem.setLastUpdated(new Date());
            xsdDao.save(xsdItem);
        } else {
            Xsd xsdTemp = this.xsdDao.get(xsdItem.getId());
            if (xsdTemp.equals("ygk")) {
                result = "success";
            } else {
                Cght cght = xsdItem.getXsht().getZddhcght();
                List<Map> bzjMaps = skshDao.findBzjblFromXsdId(xsdItem.getId());
                Double bzjBl = ((BigDecimal) bzjMaps.get(0).get("BZJBL")).doubleValue();
                if (xsd.getSkList() != null && xsd.getSkList().size() > 0) {
                    result = bindProRataBond(cght, xsd.getSkList(), bzjBl / 100, xsdItem);
                    if (result.equals("success")) {
                        xsdItem.setZt("ygk");
                        xsdItem.setLastUpdated(new Date());
                        xsdDao.save(xsdItem);
                    }
                } else {
                    result = "没有要配款的收付款金额！";
                }
            }
        }
        return result;
    }

    /**
     * 保存挂款收付款
     *
     * @param cght
     * @param skList
     * @param bzjBl
     * @param xsdItem
     * @return
     */
    public String bindProRataBond(Cght cght, List<Sfk> skList, Double bzjBl, Xsd xsdItem) {
        try {
            //先扣除挂款贴息
            for (Sfk sfk : skList) {
                Sfk clone = this.skshDao.get(sfk.getId());
                Sjzdz fkfs = this.sjzdzDao.get(clone.getFkfs().getId());
                if (fkfs.getZ().equals("承兑")) {
                    long calDays;
                    long reduceDays = DateUtil.getDay(clone.getEndDate(), clone.getKhfksj());
                    calDays = reduceDays - clone.getMxts();
                    Double tx = 0.0;
                    if (calDays > 0) {
                        tx = CalcUtils.round(((clone.getSfje() * clone.getTxl() / 100) / 30.0) * calDays, 2);
                    }
                    clone.setTx(CalcUtils.round(tx, 2));
                    clone.setTxye(CalcUtils.round(tx, 2));
                    clone.setJstx(calDays);
                    clone.setYe(CalcUtils.round(clone.getSfje() - tx, 2));
                    clone.setSfjstx("1");
                } else {
                    clone.setYe(clone.getSfje());
                }
            }

            // 总货款
            Double zhk = 0.0;
            for (Xsmx xsmx : xsdItem.getXsmxList()) {
                Double sum = CalcUtils.mulDouble(xsmx.getHsj(), xsmx.getSbsl());
                zhk += sum;
            }
            zhk = CalcUtils.round(zhk, 2);
            // 总挂款金额
            Double gkje = 0.0;
            Double bzjJe = 0.0;
            List<Sfk> sfkListTemp = new ArrayList<Sfk>();
            for (Sfk sfk : skList) {
                Sfk tmepSfk = this.skshDao.get(sfk.getId());
                bzjJe += CalcUtils.mulDouble(bzjBl, tmepSfk.getYe());
                gkje += CalcUtils.round(tmepSfk.getYe(), 2);
                sfkListTemp.add(tmepSfk);
            }
            gkje = CalcUtils.round(gkje + bzjJe, 2);
            // 判断能不能放货
            if (gkje >= zhk) {
                boolean bool = false;
                for (Sfk tmepSfk : sfkListTemp) {
                    String reslut;
                    Double syje;
                    if (tmepSfk.getFkfs().getBm().equals("1")) {
                        reslut = this.skshDao.executeDLFBZ(tmepSfk.getId(), xsdItem.getId(), DateUtil.getDate(cght.getFksj()), 9L);
                    } else {
                        reslut = this.skshDao.executeDLFBZ(tmepSfk.getId(), xsdItem.getId(), DateUtil.getDate(cght.getFksj()), 8L);
                    }
                    if (CalcUtils.round(tmepSfk.getYe(), 2) <= zhk) {
                        syje = CalcUtils.round(tmepSfk.getYe(), 2);
                        zhk -= CalcUtils.round(tmepSfk.getYe(), 2);
                        tmepSfk.setYe(0.0);
                    } else {
                        syje = zhk;
                        tmepSfk.setYe(CalcUtils.round(tmepSfk.getYe() - syje, 2));
                        bool = true;
                    }
                    this.skshDao.save(tmepSfk);
                    Ablbzjgk ablbzjgk = new Ablbzjgk();
                    ablbzjgk.setXsht_id(xsdItem.getXsht().getId());
                    ablbzjgk.setXsd_id(xsdItem.getId());
                    ablbzjgk.setSfk_id(tmepSfk.getId());
                    ablbzjgk.setYe(syje);
                    ablbzjgk.setJe(syje);
                    ablbzjgk.setBz(0l);
                    ablbzjgk.setDlfje(0.0);
                    ablbzjgk.setDeleted(0);
                    ablbzjgk.setKhfksj(reslut.split(",")[1]);
                    ablbzjgk.setTzfksj(reslut.split(",")[2]);
                    ablbzjgk.setSjzyts(Long.valueOf(reslut.split(",")[3]));
                    ablbzjgk.setJszyts(Long.valueOf(reslut.split(",")[4]));
                    ablbzjgk.setDATE_CREATED(new Date());
                    // 判断是保证金还是货款
                    if (tmepSfk.getKxsy().getZ().equals("货款")) {
                        ablbzjgk.setFklx(0l);
                        ablbzjgk.setDlfbz(Double.valueOf(reslut.split(",")[0]));
                    } else {
                        ablbzjgk.setFklx(1l);
                        ablbzjgk.setDlfbz(0.0);
                    }
                    this.ablbzjshDao.save(ablbzjgk);
                    if (bool) {
                        break;
                    }
                }
                // 使用保证金金额
                if (!bool) {
                    if (zhk > bzjJe) {
                        return "货款不满足不能进行挂款,差额：" + (CalcUtils.round(zhk - bzjJe, 2)) + "，不能进行挂款，请充值！";
                    }
                }
                return "success";
            } else {
                return "货款和释放保证金金额:" + gkje + "，差额：" + (CalcUtils.round(zhk - gkje, 2)) + "，不能进行挂款，请充值！";
            }

        } catch (
                Exception e
                )

        {
            System.out.print(e.getMessage());
            throw new RuntimeException("挂款异常！");
        }

    }

    /**
     * 进行配款操作
     *
     * @param xsdItem
     */
    @Transactional
    public String proRataAllocatePay(Xsd xsdItem) {
        // 1.调用存储过程配款，并记录表中，计费明细表
        String pkResult = this.skshDao.getPkResult(xsdItem.getId(), xsdItem.getXsht().getId(), xsdItem.getKh().getId(), xsdItem.getXsht().getZddhcght().getId());
        if (pkResult.equals("0")) {
            Xsd xsd = this.xsdDao.get(xsdItem.getId());
            xsd.setZt("ypk");
            xsdDao.save(xsd);
        }
        return pkResult;
    }

//===================================按比例释放保证金end===================================================================

    /**
     * 执行实际结算价关联
     *
     * @param xsdId
     */
    @Transactional
    public void executeActualPrice(Long xsdId) throws Exception {
        Xsd xsd = xsdDao.get(xsdId);
        Cght cght = xsd.getXsht().getZddhcght();
        if (cght.getSfhdj() != null) {
            if (cght.getSfhdj()) {
                //1、先校验该销售单下的销售明细有没有维护sjdj
                for (Xsmx xsmx : xsd.getXsmxList()) {
                    if (xsmx.getSjdj() == null || xsmx.getSjdj() == 0)
                        throw new RuntimeException("销售子项号为：" + xsmx.getXsxt_xsdh() + "没有维护实际结算价！");
                }
            }
        } else {
            for (Xsmx xsmx : xsd.getXsmxList()) {
                xsmx.setSjdj(xsmx.getHsj());
                this.xsmxDao.save(xsmx);
            }
        }
    }

//===================================无保证金start=========================================================================

    /**
     * 判断是否满足放货，并挂款
     *
     * @param xsdItem
     * @param xsd
     * @return
     */
    @Transactional
    public synchronized String gkNoBond(Xsd xsdItem, Xsd xsd) {
        Wbzjgk wbzjgk = this.wbzjshDao.findNoBondGk(xsdItem);
        String result;
        // 判断是否重复点击
        if (null != wbzjgk) {
            result = "success";
        } else {
            List<Sfk> sfkList;
            Xsd xsdTemp = this.xsdDao.get(xsdItem.getId());
            if (xsdTemp.equals("ygk")) {
                result = "success";
            } else {
                if (xsd.getSkList() != null && xsd.getSkList().size() > 0) {
                    Cght cght = xsdItem.getXsht().getZddhcght();
                    sfkList = xsd.getSkList();
                    result = bindNobondSfk(cght, xsdItem, sfkList);
                    if (result.equals("success")) {
                        xsdItem.setZt("ygk");
                        xsdItem.setLastUpdated(new Date());
                        xsdDao.save(xsdItem);
                    }
                } else {
                    result = "没有选择挂款信息！";
                }
            }
        }

        return result;
    }

    /**
     * 无保证金模式，判断是否满足并挂款
     *
     * @param cght
     * @param xsdItem
     * @param sfkList
     * @return
     */
    private String bindNobondSfk(Cght cght, Xsd xsdItem, List<Sfk> sfkList) {
        // 总货款
        String result;
        double zhk = 0.0;
        for (Xsmx xsmx : xsdItem.getXsmxList()) {
            double sum = CalcUtils.mulDouble(xsmx.getHsj(), xsmx.getSbsl()).doubleValue();
            zhk += sum;
        }
        // 总挂款金额
        double gkje = 0.0;
        for (Sfk sfk : sfkList) {
            // 页面绑定的是合同货款id
            Hthk hthk = this.hthkDao.get(sfk.getId());
            gkje += hthk.getYe();
        }

        // 判断是否满足放货
        if (CalcUtils.round(zhk, 2) > CalcUtils.round(gkje, 2)) {
            result = "挂款金额小于货款,差额为：" + (CalcUtils.round(zhk, 2) - CalcUtils.round(gkje, 2)) + "，不能进行挂款操作！";
        } else {
            boolean bool = false;
            for (Sfk sfk : sfkList) {
                // sfk.getId() 为合同货款id
                Hthk hthk = this.hthkDao.get(sfk.getId());
                double je;
                // 挂款操作
                double kyye = CalcUtils.round(hthk.getYe(), 2);
                if (kyye <= zhk) {
                    je = CalcUtils.round(hthk.getYe(), 2);
                    zhk -= CalcUtils.round(hthk.getYe(), 2);
                    hthk.setYe(0.0);
                } else {
                    je = zhk;
                    hthk.setYe(CalcUtils.round(hthk.getYe() - je, 2));
                    bool = true;
                }
                this.hthkDao.save(hthk);

                Wbzjgk wbzjgk = new Wbzjgk();
                wbzjgk.setXsht_id(xsdItem.getXsht().getId());
                wbzjgk.setXsd_id(xsdItem.getId());
                wbzjgk.setSfk_id(hthk.getSk().getId());
                wbzjgk.setJe(je);
                wbzjgk.setYe(je);
                wbzjgk.setBz(0L);
                wbzjgk.setDeleted(0);
                wbzjgk.setCght_id(xsdItem.getXsht().getZddhcght().getId());
                wbzjgk.setTxl(CalcUtils.round(cght.getTxl(), 4));
                wbzjgk.setDATE_CREATED(new Date());
                this.wbzjshDao.save(wbzjgk);
                if (bool) {
                    break;
                }
            }
            result = "success";
        }
        return result;
    }

    /**
     * 配款操作
     *
     * @param xsdItem
     * @param kh
     */
    @Transactional
    public String noBondAllocatePay(Xsd xsdItem, Qyjg kh) {
        // 1.调用存储过程配款，并记录表中，计费明细表
        String pkResult = this.skshDao.wbzjPk(xsdItem.getId(), xsdItem.getXsht().getId(), kh.getId(), xsdItem.getXsht().getZddhcght().getId());
        if (pkResult.equals("0")) {
            Xsd xsd = this.xsdDao.get(xsdItem.getId());
            xsd.setZt("ypk");
            xsdDao.save(xsd);
        }
        return pkResult;
    }

//===================================无保证金start=========================================================================

    @Transactional
    public void cancelexamineXsd(Long xsdId) {
        Xsd xsd = this.xsdDao.get(xsdId);
        xsd.setCwsh(false);
        xsd.setShsj(new Date());
        xsd.setShr(YgService.getCurrentYg());
        this.xsdDao.save(xsd);
    }


    /**
     * 查询销售单明细
     *
     * @param xsdId 销售单ID
     * @return
     */
    public String findXsmxDetail(Long xsdId) {
        Gson gson = new Gson();
        java.text.DecimalFormat jtdf = new java.text.DecimalFormat("#0.00");
        java.text.DecimalFormat df = new java.text.DecimalFormat("#0.0000");
        List<Map> xsdmxList = this.xsdDao.findXsmxList(xsdId);
        Integer js = 0;
        Double xscb = 0d;
        Double sbsl = 0d;
//        Double hsj = 0d;
//        Double bhsj = 0d;
        Double bhse = 0d;
        Double hse = 0d;
        Double xscbzh = 0d;
//        Double xslr = 0d;
        Double ghje = 0d;
        Double zjfpzje = 0d;
        String result = "";
        if (xsdmxList.size() > 0) {
            for (Map map : xsdmxList) {
                js += map.get("js") == null ? 0 : Integer.parseInt(map.get("js").toString());
                xscb += map.get("xscb") == null ? 0d : Double.parseDouble(map.get("xscb").toString());
                sbsl += map.get("sbsl") == null ? 0d : Double.parseDouble(map.get("sbsl").toString());
//                hsj += map.get("hsj") == null ? 0d : Double.parseDouble(map.get("hsj").toString());
                hse += (map.get("hsj") == null ? 0d : Double.parseDouble(map.get("hsj").toString())) * (map.get("sbsl") == null ? 0d : Double.parseDouble(map.get("sbsl").toString()));
//                bhsj += map.get("bhsj") == null ? 0d : Double.parseDouble(map.get("bhsj").toString());
                bhse += (map.get("bhsj") == null ? 0d : Double.parseDouble(map.get("bhsj").toString())) * (map.get("sbsl") == null ? 0d : Double.parseDouble(map.get("sbsl").toString()));
                xscbzh += map.get("xscbzh") == null ? 0d : Double.parseDouble(map.get("xscbzh").toString());
//                xslr += map.get("xslr") == null ? 0d : Double.parseDouble(map.get("xslr").toString());
                ghje += map.get("ghje") == null ? 0d : Double.parseDouble(map.get("ghje").toString());
                zjfpzje += map.get("zjfpje") == null ? 0d : Double.parseDouble(map.get("zjfpje").toString());
            }
            result = "{\"rows\":" + gson.toJson(xsdmxList) + ",\"footer\":[{\"kh.khbm\":\"合计:\",\"js\":" + js
                    + ",\"xscb\":" + xscb + ",\"sbsl\":" + sbsl + ",\"zjfpje\":" + zjfpzje + ",\"hse\":" + hse + ",\"bhse\":" + bhse + ",\"xscbzh\":" + xscbzh + "}]}";
        } else {
            result = "{\"rows\":" + gson.toJson(xsdmxList) + "}]}";
        }
        return result;
    }

    /**
     * 查询销售单明细(结算)
     *
     * @param xsdId 销售单ID
     * @return
     */
    public String findXsmxJsDetail(Long xsdId) {
        Gson gson = new Gson();
        List<Map> xsdmxList = this.xsdDao.findXsmxJsList(xsdId);
        if (xsdmxList.size() == 0) {
            xsdmxList = this.xsdDao.findXsmxJsList1(xsdId);
        }
        Integer js = 0;
        Double xscb = 0d;
        Double sbsl = 0d;
        Double hsj = 0d;
        Double bhsj = 0d;
        Double bhse = 0d;
        Double hse = 0d;
        String result;
        if (xsdmxList.size() > 0) {
            for (Map map : xsdmxList) {
                js += map.get("js") == null ? 0 : Integer.parseInt(map.get("js").toString());
                xscb += map.get("xscb") == null ? 0d : Double.parseDouble(map.get("xscb").toString());
                sbsl += map.get("cksl") == null ? 0d : Double.parseDouble(map.get("cksl").toString());
                hsj += map.get("hsj") == null ? 0d : Double.parseDouble(map.get("hsj").toString());
                hse += (map.get("hsj") == null ? 0d : Double.parseDouble(map.get("hsj").toString())) * (map.get("cksl") == null ? 0d : Double.parseDouble(map.get("cksl").toString()));
                bhsj += map.get("bhsj") == null ? 0d : Double.parseDouble(map.get("bhsj").toString());
                bhse += (map.get("bhsj") == null ? 0d : Double.parseDouble(map.get("bhsj").toString())) * (map.get("cksl") == null ? 0d : Double.parseDouble(map.get("cksl").toString()));
            }
            result = "{\"rows\":" + gson.toJson(xsdmxList) + ",\"footer\":[{\"kh.khbm\":\"合计:\",\"js\":" + js
                    + ",\"xscb\":" + xscb + ",\"cksl\":" + sbsl + ",\"hsj\":" + hsj + ",\"bhsj\":" + bhsj + ",\"hse\":" + hse + ",\"bhse\":" + bhse + "}]}";
        } else {
            result = "{\"rows\":" + gson.toJson(xsdmxList) + "}]}";
        }
        return result;
    }


    /**
     * 查询销售单明细
     *
     * @param kh 卡号
     * @return
     */
    public List<Map> findXsmxByKh(Kh kh) {
        return this.xsdDao.findXsmxByKh(kh);
    }


    /**
     * 销售单挂款明细
     *
     * @param xsdId
     * @return
     */
    public String findXsdgkmx(Long xsdId) {
        Gson gson = new Gson();
        String result;
        Xsd xsd = this.xsdDao.get(xsdId);
        List<Map> xsdGkmxList = this.xsdDao.findXsdgkmx(xsd);
        Double zje = 0.0;
        if (null != xsdGkmxList && xsdGkmxList.size() > 0) {
            for (Map map : xsdGkmxList) {
                zje += map.get("SJJE") == null ? 0d : Double.parseDouble(map.get("SJJE").toString());
            }
            result = "{\"rows\":" + gson.toJson(xsdGkmxList) + ",\"footer\":[{\"BM\":\"合计:\",\"SJJE\":" + zje + "}]}";
        } else {
            result = "{\"rows\":" + gson.toJson(xsdGkmxList) + "}";
        }
        return result;
    }

    /**
     * 计费明细
     *
     * @param xsdId 销售单ID
     * @return
     */
    public String findJfmxDetail(Long xsdId) {
        Gson gson = new Gson();
        String result;
        Double zl = 0d;
        Double dlfje = 0d;
        Double ghje = 0d;
        Double sfje = 0d;
        Double tx = 0d;
        Double ghzje = 0d;
        List<Map> xsdjfmxList = this.xsdDao.findJfmxList(xsdId);
        if (null != xsdjfmxList && xsdjfmxList.size() > 0) {
            for (Map map : xsdjfmxList) {
                zl += map.get("ZL") == null ? 0d : Double.parseDouble(map.get("ZL").toString());
                ghje += map.get("GHJE") == null ? 0d : Double.parseDouble(map.get("GHJE").toString());
                sfje += map.get("SFJE") == null ? 0d : Double.parseDouble(map.get("SFJE").toString());
                dlfje += map.get("DLFJE") == null ? 0d : Double.parseDouble(map.get("DLFJE").toString());
                tx += map.get("TXJE") == null ? 0d : Double.parseDouble(map.get("TXJE").toString());
                ghzje += map.get("GHZJE") == null ? 0d : Double.parseDouble(map.get("GHZJE").toString());
            }
            result = "{\"rows\":" + gson.toJson(xsdjfmxList) + ",\"footer\":[{\"NAME\":\"合计:\",\"ZL\":" + zl + ",\"GHJE\":" + ghje + ",\"SFJE\":" + sfje + ",\"DLFJE\":" + dlfje + ",\"TXJE\":" + tx + ",\"GHZJE\":" + ghzje + "}]}";
        } else {
            result = "{\"rows\":" + gson.toJson(xsdjfmxList) + "}";
        }
        return result;
    }


    /**
     * 查询销售单费用
     *
     * @param xsdId 销售单ID
     * @return
     */
    public String findXsfyDetail(Long xsdId) {
        Gson gson = new Gson();
        String result = "";
        Double jfsl = 0d;
        Double je = 0d;
        List<Map> xsdfyList = this.xsdDao.findXsfyList(xsdId);
        if (xsdfyList.size() > 0) {
            for (Map map : xsdfyList) {
                jfsl += map.get("jfsl") == null ? 0d : Double.parseDouble(map.get("jfsl").toString());
                je += map.get("je") == null ? 0d : Double.parseDouble(map.get("je").toString());
            }
            result = "{\"rows\":" + gson.toJson(xsdfyList) + ",\"footer\":[{\"fylb.fykmjc\":\"合计:\",\"jfsl\":" + jfsl
                    + ",\"je\":" + je + "}]}";
        } else {
            result = "{\"rows\":" + gson.toJson(xsdfyList) + "}";
        }
        return result;
    }


    /**
     * 保存销售明细
     *
     * @param xsmx
     */
    @Transactional
    public void saveXsmx(Xsmx xsmx) {
        this.xsmxDao.save(xsmx);
    }

    /**
     * 保存销售单信息
     *
     * @param xsd 销售单
     * @return
     */
    @Transactional
    public void saveXsd(Xsd xsd) throws SQLException {
        java.text.DecimalFormat jtdf = new java.text.DecimalFormat("#0.00");
        java.text.DecimalFormat df = new java.text.DecimalFormat("#0.0000");
        xsd.setXsdh(xsdBm(xsd));
        if (xsd.getSl() != null) {
            String sl = df.format(xsd.getSl());
            xsd.setSl(Double.parseDouble(sl));
        }
        xsd.setZt("ybc");
        xsd.setCreateUser(YgService.getCurrentYg());
        xsd.setCreateOrgan(YgService.getCurrentYg().getZggs());
        xsd.setCreateDepartment(YgService.getCurrentYg().getZgjg());
        xsd.setDateCreated(new Date());
        xsd.setLastUpdated(xsd.getDateCreated());
        Xsht xsht = this.xshtDao.get(xsd.getXsht().getId());

        if (StringUtils.isNotBlank(xsht.getOrderId())) {
            xsd.setOrderId(xsht.getOrderId());
        }

        if (xsd.getXsmxList() != null) {
            for (Xsmx xsmx : xsd.getXsmxList()) {
                if (xsmx.getKh() != null) {
                    Kh kh = khDao.get(xsmx.getKh().getId());
                    kh.setYbc(1);
                    khDao.save(kh);
                    xsmx.setJtwz(kh.getJtwz());
                    xsmx.setXsxt_xsdh(kh.getXsxt_xsdh());//销售系统子项号
                    // xsmx.setXsxt_price(kh.getXsxt_price());
                    xsmx.setXsxt_fhrq(kh.getXsxt_fhrq());//发货日期
                    xsmx.setBindNo(kh.getBindNo());//捆包号
                    xsmx.setXsxt_htbm(kh.getXsxt_htbm());//来源系统合同号
                    xsmx.setCarNo(kh.getCarNo());//车号
                    xsd.getXsht().getHtmxList();
                    // 如果实际单价已经导入，赋值实际单价给销售明细
                    if (StringUtils.equals("1", kh.getSfdrjg())) {
                        xsmx.setSjdj(kh.getXsxt_price());
                    }
                }
             /*   for(Htmx htmx : xsht.getHtmxList()){
                    if(htmx.getWzgg().getId() == xsmx.getJtwz().getId()){
                        htmx.setYxz(1);
                        htmxDao.save(htmx);

                    }
                }*/


                xsmx.setBhsj(CalcUtils.round(xsmx.getBhsj(), 2));
                xsmx.setHsj(CalcUtils.round(xsmx.getHsj(), 2));
                xsmx.setSbsl(CalcUtils.round(xsmx.getSbsl(), 6));
                xsmx.setCk_sbsl(CalcUtils.round(xsmx.getCk_sbsl(), 6));
                xsmx.setJsbhse(CalcUtils.round(xsmx.getJsbhse(), 2));
                xsmx.setJsse(CalcUtils.round(xsmx.getJsse(), 2));
                xsmx.setXscb(CalcUtils.round(xsmx.getXscb(), 2));
                xsmx.setCkbhse(CalcUtils.round(xsmx.getCkbhse(), 2));
                xsmx.setSjghje(CalcUtils.round(xsmx.getSjghje(), 2));
                xsmx.setKpbhsj(CalcUtils.round(xsmx.getKpbhsj(), 2));
                xsmx.setXsxt_price(CalcUtils.round(xsmx.getXsxt_price(), 2));
                xsmx.setDateCreated(new Date());
                xsmx.setLastUpdated(xsmx.getDateCreated());
                xsmx.setCreateUser(YgService.getCurrentYg());
                xsmx.setCreateOrgan(xsd.getCreateOrgan());
                xsmx.setCreateDepartment(xsd.getCreateDepartment());
            }
        }
        if (xsd.getXsfyList() != null && xsd.getXsfyList().size() != 0) {
            for (Glfy glfy : xsd.getXsfyList()) {
                String je = jtdf.format(glfy.getJe());
                glfy.setJe(Double.valueOf(je));
                glfy.setDateCreated(new Date());
                glfy.setLastUpdated(new Date());
                glfy.setCreateUser(YgService.getCurrentYg());
                glfy.setCreateOrgan(xsd.getCreateOrgan());
                glfy.setCreateDepartment(xsd.getCreateDepartment());
                glfyDao.save(glfy);
            }
        }
        this.xsdDao.save(xsd);
        createCgdFromXsd(xsd);
    }


    @Transactional
    public void saveXsdtk(Xsd xsd, Xsd qxsd, Double htce) throws SQLException {
        java.text.DecimalFormat jtdf = new java.text.DecimalFormat("#0.00");
        java.text.DecimalFormat df = new java.text.DecimalFormat("#0.0000");
        Double temp;

        for (Sfk sfk : qxsd.getSkList()) {
            Long id = sfk.getId();
            sfk = skshService.findSkshDetail(id);
            String ye = jtdf.format(sfk.getYe());
            sfk.setYe(Double.valueOf(ye) + Double.valueOf(htce));
       /*
                Jfmx j = new Jfmx();
                j.setXsd(xsd);
                j.setXsht(xsd.getXsht());
                j.setGhje(sfk.getYe());
                j.setSfk(sfk);
                jfmxDao.save(j);
                */
            Tkmx t = new Tkmx();
            t.setKh(xsd.getKh());
            t.setXsd(xsd);
            t.setXsht(xsd.getXsht());
            t.setTkje(sfk.getYe());
            t.setSfk(sfk);
            t.setCreated_date(new Date());
            tkmxDao.save(t);
            skshDao.save(sfk);
        }
        //  xsd.setZt("ytk");
        this.xsdDao.save(xsd);
    }

    private void createCgdFromXsd(Xsd xsd) {
        Cgd cgd = new Cgd();
        cgd.setCgdh(bmService.getCgdbm("cgrk"));
        cgd.setBz("此采购单根据销售单" + xsd.getXsdh() + "自动生成");
        cgd.setCggs(xsd.getKh());
        cgd.setGys(xsd.getXsgs());
        cgd.setLastUpdated(new Date());
        cgd.setCgsj(new Date());
        cgd.setFhrq(new Date());
        cgd.setJhdhrq(new Date());
        cgd.setDzck(xsd.getThck());
        cgd.setYsh(true);
        cgd.setZt("ysp");
        cgd.setYrk(true);
        cgd.setRksj(new Date());
//        cgd.setRkr(YgService.getCurrentYg());
        cgd.setLj(xsd.getLj());
        cgd.setCglx("cgrk");
        cgd.setSl(xsd.getSl().toString());
        cgd.setSbgs(xsd.getKh());
        cgd.setLastUpdated(cgd.getDateCreated());
//        if(YgService.getCurrentYg() == null){
//            cgd.setCreateDepartment();
//        }else{
//            cgd.setCreateDepartment(YgService.getCurrentYg().getZgjg());
//        }
        try {
            cgd.setCreateOrgan(YgService.getCurrentYg().getZggs());
            cgd.setCreateUser(YgService.getCurrentYg());
            cgd.setRkr(YgService.getCurrentYg());
            cgd.setSbr(YgService.getCurrentYg());
        } catch (Exception e) {
            cgd.setCreateOrgan(this.gsjgDao.get(24L));
        }


        List<Cgdmx> cgdmxList = new ArrayList<Cgdmx>();
        Long n = 1l;
        for (Xsmx xsmx : xsd.getXsmxList()) {
            Cgdmx cgdmx = new Cgdmx();
            cgdmx.setGg(xsmx.getJtwz());
            cgdmx.setHsj(CalcUtils.round(xsmx.getHsj(), 4));
            cgdmx.setBhsj(CalcUtils.round(xsmx.getBhsj(), 4));
            cgdmx.setSbsl(CalcUtils.round(xsmx.getSbsl(), 6));
            cgdmx.setJs(xsmx.getJs());
            cgdmx.setRkjs(xsmx.getJs());
            cgdmx.setRksl(CalcUtils.round(xsmx.getSbsl(), 6));
            cgdmx.setCgd(cgd);
            Sjzdz cd = khDao.get(xsmx.getKh().getId()).getCd();
            cgdmx.setCd(cd);
            cgdmx.setKh(xsmx.getKh());
            cgdmx.setJzfs(xsmx.getJzfs());
            cgdmx.setMxh(n);
            cgdmx.setLastUpdated(cgdmx.getDateCreated());

            try {
                cgdmx.setCreateUser(YgService.getCurrentYg());
                cgdmx.setCreateDepartment(YgService.getCurrentYg().getZgjg());
                cgdmx.setCreateOrgan(YgService.getCurrentYg().getZggs());
            } catch (Exception e) {
                cgdmx.setCreateOrgan(this.gsjgDao.get(24L));
            }

            n++;
            cgdmxList.add(cgdmx);
        }
        cgd.setCgdmxList(cgdmxList);
        cgdDao.save(cgd);
    }

    public String xsdBm(Xsd xsd) {
        return this.bmService.getXsdbm(xsd.getXslx());
    }

    /**
     * 查询销售单明细
     *
     * @param id
     * @return
     */
    public List<Xsmx> getXsmx(Long id) {
        return this.xsmxDao.getXsmx(id);
    }

    /**
     * 修改销售单信息
     *
     * @param xsd 销售单
     * @return
     */
    @Transactional
    public void editXsd(Xsd xsd, String xsdbm, List<Xsmx> mxList) {
        xsd.setXsdh(xsdbm);
        if (xsd.getSl() != null) {
            java.text.DecimalFormat df = new java.text.DecimalFormat("#0.0000");
            String sl = df.format(xsd.getSl());
            xsd.setSl(Double.parseDouble(sl));
        }
        if (StringUtils.isEmpty(xsd.getZt()))
            xsd.setZt("ybc");
        xsd.setLastUpdated(new Date());
        if (xsd.getXsmxList() != null) {
            Long count = 0l;
            // 改变卡号保存状态
            boolean bool = false;
            for (Xsmx m : mxList) {
                for (Xsmx xsmx : xsd.getXsmxList()) {
                    if (m.getKh().getId().equals(xsmx.getKh().getId())) {
                        bool = false;
                        break;
                    } else {
                        bool = true;
                    }
                }

                if (bool) {
                    Kh h = khDao.get(m.getKh().getId());
                    h.setYbc(0);
                    this.khDao.save(h);
                }
            }
            for (Xsmx xsmx : xsd.getXsmxList()) {
                if (xsmx.getKh() != null) {
                    Kh kh = khDao.get(xsmx.getKh().getId());
                    xsmx.setJtwz(kh.getJtwz());
                    xsmx.setXsxt_xsdh(kh.getXsxt_xsdh());//销售系统子项号
                    // xsmx.setXsxt_price(kh.getXsxt_price());
                    xsmx.setXsxt_fhrq(kh.getXsxt_fhrq());//发货日期
                    xsmx.setBindNo(kh.getBindNo());//捆包号
                    xsmx.setXsxt_htbm(kh.getXsxt_htbm());//来源系统合同号
                    xsmx.setCarNo(kh.getCarNo());//车号
                    if (xsd.getXslx().equals("bgxs")) {
                        xsmx.setBhsj(kh.getWsdj() * 1.017);
                        xsmx.setHsj(kh.getWsdj() * 1.017 * 1.17);
                    }
                }

                if (xsmx.getMxh() == null) {
                    xsmx.setMxh(count + 1);
                }
                xsmx.setLastUpdated(new Date());
                count++;
            }
        }
        this.xsdDao.save(xsd);
    }

    /**
     * 成本价格调整
     */
    @Transactional
    public void cbjgtz(Xsd xsd) {
        Xsd x = xsdDao.get(xsd.getId());
        if (!x.getYck()) {
            throw new RuntimeException("销售单未出库，不能进行调整！");
        }
        if (x.getXslx().equals("bgxs")) {
            throw new RuntimeException("保供销售单不能进行调整！");
        }
        for (Xsmx xsmx : xsd.getXsmxList()) {
            Xsmx mx = xsmxDao.get(xsmx.getId());
            if (mx.getXscb().doubleValue() != xsmx.getXscb().doubleValue()) {
                Zjbcd zjbcd = new Zjbcd();
                Sjzdz sjzdz = new Sjzdz();
                sjzdz.setId(50L);
                zjbcd.setLb(sjzdz);
                java.text.DecimalFormat df = new java.text.DecimalFormat("#0.0000");
                String slstr = df.format((xsmx.getXscb() - mx.getXscb()) * mx.getCk_sbsl());
                zjbcd.setJe(Double.parseDouble(slstr));
                if (mx.getKh() != null && mx.getKh().getGys() != null)
                    zjbcd.setGys(mx.getKh().getGys());
                else if (x.getXslx().equals("zddh")) {
                    Cgd cgd = this.cgdDao.findUniqueByProperty("xsd.id", xsd.getId());
                    zjbcd.setGys(cgd.getGys());
                } else {
                    Gsjg gsjg = new Gsjg();
                    gsjg.setId(-1l);
                    zjbcd.setGys(gsjg);
                }

                zjbcd.setZt("ybc");
                zjbcd.setCreateUser(YgService.getCurrentYg());
                zjbcd.setDateCreated(new Date());
                zjbcd.setLastUpdated(zjbcd.getDateCreated());
                zjbcd.setCreateDepartment(YgService.getCurrentYg().getZgjg());
                zjbcd.setCreateOrgan(YgService.getCurrentYg().getZggs());
                zjbcd.setSftzsc(true);
                zjbcdDao.save(zjbcd);
                ZjbcdRz zjbcdRz = new ZjbcdRz();
                zjbcdRz.setXsd(x);
                zjbcdRz.setXsmx(mx);
                zjbcdRz.setZjbcd(zjbcd);
                zjbcdRz.setYkccb(mx.getXscb());
                zjbcdRz.setXkccb(xsmx.getXscb());
                zjbcdRz.setCreateUser(YgService.getCurrentYg());
                zjbcdRz.setDateCreated(new Date());
                zjbcdRz.setLastUpdated(zjbcdRz.getDateCreated());
                zjbcdRz.setCreateDepartment(YgService.getCurrentYg().getZgjg());
                zjbcdRz.setCreateOrgan(YgService.getCurrentYg().getZggs());
                zjbcdRzDao.save(zjbcdRz);
                mx.setXscb(xsmx.getXscb());
                mx.setLastUpdated(new Date());
                xsmxDao.save(mx);
            }
        }
    }

    /**
     * 提交销售单
     *
     * @param xsd  销售单
     * @param type self：自提放货，goods：货权转移
     * @return
     */
    @Transactional
    public void commitXsd(Xsd xsd, String type) {
        Jkpz jkpz = jkpzDao.findByBm("xsd");
        if (jkpz.getFlag()) {
            String result = "";
            Gson gson = new Gson();
            if (StringUtils.isNotEmpty(xsd.getOrderId())) {
                String json = createGoodsOrderJson(xsd);
                result = "[{\"code\":\"0\",\"message\":\"成功！\"}]";
//              result = this.webserviceTransService.transXsdGdWebServiceArgs(xsd.getSbgs().getBm(), json);//线上订单传向仓储
            } else {
                String json = createGoodsNoticeJson(xsd, type);
                result = this.webserviceTransService.transXsdWebServiceArgs(json);// 线下订单提交仓储放货
            }
            if (StringUtils.isNotEmpty(result)) {
                Map<String, Object> resultMap = new HashMap<String, Object>();
                try {
                    resultMap = gson.fromJson(result, new TypeToken<Map<String, Object>>() {
                    }.getType());
                } catch (Exception e) {
                    List<Map<String, Object>> mapList = gson.fromJson(result, new TypeToken<List<Map<String, Object>>>() {
                    }.getType());
                    if (null != mapList && mapList.size() > 0) {
                        resultMap = mapList.get(0);
                    }
                }
                if (resultMap != null && resultMap.get("code").equals("0")) {
                    if (type.equals("transfer")) {
                        xsd.setZt("ytj");
                    } else {
                        this.ckshService.checkCksh(xsd);//出库操作减去库存数量
                    }

                    if (!xsd.getXslx().equals("kcls")) {
                        xsd.setCwsh(true);
                        xsd.setShr(YgService.getCurrentYg());
                        xsd.setShsj(new Date());
                    }
                    List<Xsmx> xsmxList = xsd.getXsmxList();
                    for (Xsmx xsmx : xsmxList) {
                        xsmx.setXscb(xsmx.getKh().getWsdj());
                        xsmx.setLastUpdated(new Date());
                    }
                    xsd.setLastUpdated(new Date());
                    this.xsdDao.save(xsd);
                } else {
                    throw new RuntimeException((String) resultMap.get("message"));
                }
            } else {
                throw new RuntimeException("提交的销售单到仓储接口失败,请重新提交");
            }
        } else {
            if (type.equals("transfer")) {
                xsd.setZt("ytj");
            } else {
                this.ckshService.checkCksh(xsd);//过户操作减去库存数量
            }

            if (!xsd.getXslx().equals("kcls")) {
                xsd.setCwsh(true);
                xsd.setShr(YgService.getCurrentYg());
                xsd.setShsj(new Date());
            }
            List<Xsmx> xsmxList = xsd.getXsmxList();
            for (Xsmx xsmx : xsmxList) {
                xsmx.setXscb(xsmx.getKh().getWsdj());
                xsmx.setLastUpdated(new Date());
            }
            xsd.setLastUpdated(new Date());
            this.xsdDao.save(xsd);
        }
    }

    //线下需要生成收款还有代付款销售单记录
    @Transactional(propagation = Propagation.SUPPORTS)
    private void getXsskVoid(Xsd xsd) {
        Double xse = 0.0d;
        for (Xsmx xsmx : xsd.getXsmxList()) {
            xse += xsmx.getSbsl() * xsmx.getHsj();
        }
        if (xsd.getOrderId() == null) {
            //借方二级账户
            Ejzh jfzjzh = ejzhDao.findKyyeByKhId(xsd.getSbgs().getId(), xsd.getSbgs().getId());
            //贷方二级账户
            Ejzh dfzjzh = ejzhDao.findKyyeByKhId(xsd.getKh().getId(), xsd.getSbgs().getId());
            if (jfzjzh == null) {
                throw new RuntimeException("销售单" + xsd.getXsdh() + "申报公司二级账户为空");
            }
            if (dfzjzh == null) {
                throw new RuntimeException("销售单" + xsd.getXsdh() + "客户二级账户为空");
            }
            //新增代付款销售单保存锁定数据
            Dfkxsd dfkxsd = new Dfkxsd();
            dfkxsd.setXsd(xsd);
            dfkxsd.setDateCreated(new Date());
            dfkxsd.setLastUpdated(dfkxsd.getDateCreated());
            dfkxsd.setDeleted(1);
            //新增收款
            Sfk sfk = new Sfk();
            sfk.setSbgs(xsd.getSbgs());
            sfk.setGldw(xsd.getKh());
            //外部付款
            sfk.setWlzlx(1);
            sfk.setDateCreated(new Date());
            sfk.setSfje(xse);
            sfk.setLastUpdated(sfk.getDateCreated());
            sfk.setCreateUser(null);
            sfk.setCreateOrgan(null);
            sfk.setCreateDepartment(null);
            sfk.setBm(this.bmService.getSfdbm("SK"));
            sfk.setSfklx(3);//销售收款
            sfk.setKxlx(4);//应收款
            Sjzdz pjlx = new Sjzdz();
            pjlx.setId(144L);
            sfk.setPjlx(pjlx);//票据类型  其他
            Sjzdz kxyt = new Sjzdz();
            kxyt.setId(132L);
            sfk.setKxyt(kxyt);
            sfk.setNbkhh(dfzjzh.getKhh());
            sfk.setShrq(new Date());
            sfk.setZt("ysh");
            sfk.setSfkrq(new Date());
            dfkxsd.setMessage("销售收款");
            dfkxsd.setXssk(sfk);
            dfkxsdDao.save(dfkxsd);
            //贷方二级账户，买方二级账户
            sfk.setDfejzh(dfzjzh);
            //借方二级账户，卖方二级账户
            sfk.setJfejzh(jfzjzh);
            this.skshDao.save(sfk);
            if (dfzjzh.getKyye() < xse) {
                throw new RuntimeException("二级账户" + dfzjzh.getQc() + "可用余额不足");
            }
            jfzjzh.setKyye((jfzjzh.getKyye() == null ? 0 : jfzjzh.getKyye()) + xse);
            jfzjzh.setYe((jfzjzh.getYe() == null ? 0 : jfzjzh.getYe()) + xse);
            dfzjzh.setKyye((dfzjzh.getKyye() == null ? 0 : dfzjzh.getKyye()) - xse);
            dfzjzh.setYe((dfzjzh.getYe() == null ? 0 : dfzjzh.getYe()) - xse);
            ejzhDao.save(jfzjzh);
            ejzhDao.save(dfzjzh);
        }
    }


    /**
     * 调整销售单信息
     *
     * @param xsd 销售单
     * @return
     */
    @Transactional
    public void editXsdtz(Xsd xsd, List<Xsmx> list, Xsd hcxsd, Xsd yxsd) throws
            IllegalAccessException, NoSuchMethodException, InvocationTargetException, SQLException {
        xsd.setId(null);
        xsd.setYjs(false);
        xsd.setXsjsd(null);
        hcxsd.setId(null);
        hcxsd.setYjs(false);
        hcxsd.setXsjsd(null);

        List<Xsmx> xsmxList = yxsd.getXsmxList();
        List<Glfy> xsfyList = yxsd.getXsfyList();
        Psd psd = yxsd.getPsd();

        List<Xsmx> hcxsmxList = new ArrayList<Xsmx>();
        List<Glfy> hcglfyList = new ArrayList<Glfy>();
        Psd hcpsd = null;

        for (Xsmx xsmx : xsmxList) {
            Xsmx hcxsmx = new Xsmx();
            PropertyUtils.copyProperties(hcxsmx, xsmx);
            hcxsmx.setId(null);
            hcxsmx.setSbsl(0 - xsmx.getSbsl());
            if (xsmx.getCk_js() != null)
                hcxsmx.setCk_js(0 - xsmx.getCk_js());
            hcxsmx.setCk_sbsl(0 - xsmx.getCk_sbsl());
            if (xsmx.getCkbhse() != null)
                hcxsmx.setCkbhse(0 - xsmx.getCkbhse());
            hcxsmx.setYjs(false);
            hcxsmx.setXsjsd(null);
            hcxsmx.setCreateUser(YgService.getCurrentYg());
            hcxsmx.setCreateOrgan(xsd.getCreateOrgan());
            hcxsmx.setCreateDepartment(xsd.getCreateDepartment());
            hcxsmx.setDateCreated(new Date());
            hcxsmx.setLastUpdated(xsd.getDateCreated());
            hcxsmxList.add(hcxsmx);
            if (xsmx.getKh() != null) {
                khDao.updateKhSlAdd(xsmx.getKh().getId(), xsmx.getCk_sbsl());
            }
        }
        for (Glfy xsfy : xsfyList) {
            Glfy hcxsfy = new Glfy();
            PropertyUtils.copyProperties(hcxsfy, xsfy);
            hcxsfy.setId(null);
            hcxsfy.setGlfymxList(null);
            hcxsfy.setJfsl(0 - xsfy.getJfsl());
            hcxsfy.setJe(0 - xsfy.getJe());
            hcxsfy.setCreateUser(YgService.getCurrentYg());
            hcxsfy.setCreateOrgan(xsd.getCreateOrgan());
            hcxsfy.setCreateDepartment(xsd.getCreateDepartment());
            hcxsfy.setDateCreated(new Date());
            hcxsfy.setLastUpdated(xsd.getDateCreated());
            if (xsfy.getGlfymxList() != null) {
                List<Glfymx> gylfymxList = new ArrayList<Glfymx>();
                for (Glfymx glfymx : xsfy.getGlfymxList()) {
                    Glfymx hcglfymx = new Glfymx();
                    PropertyUtils.copyProperties(hcglfymx, glfymx);
                    hcglfymx.setId(null);
                    hcglfymx.setJtfy(0 - glfymx.getJtfy());
                    hcglfymx.setJsjtfy(0 - glfymx.getJsjtfy());
                    hcglfymx.setGlfy(xsfy);
                    gylfymxList.add(hcglfymx);
                }
                hcxsfy.setGlfymxList(gylfymxList);
            }
            hcglfyList.add(hcxsfy);
        }
        if (psd != null) {
            hcpsd = new Psd();
            PropertyUtils.copyProperties(hcpsd, psd);
            hcpsd.setPsfy(0 - hcpsd.getPsfy());
            hcpsd.setCreateUser(YgService.getCurrentYg());
            hcpsd.setCreateOrgan(xsd.getCreateOrgan());
            hcpsd.setCreateDepartment(xsd.getCreateDepartment());
            hcpsd.setDateCreated(new Date());
            hcpsd.setLastUpdated(xsd.getDateCreated());
            hcpsd.setId(null);
        }

        //保存原销售单
        yxsd.setSftzd(true);
        yxsd.setYxsd(yxsd);
        yxsd.setLastUpdated(new Date());

        //保存红冲的销售单
        hcxsd.setXsdh(xsdBm(hcxsd));
        hcxsd.setSftzd(true);
        hcxsd.setXsmxList(hcxsmxList);
        hcxsd.setXsfyList(hcglfyList);
        hcxsd.setPsd(hcpsd);
        hcxsd.setCksj(new Date());
        hcxsd.setDateCreated(new Date());
        hcxsd.setCreateUser(YgService.getCurrentYg());
        hcxsd.setCreateOrgan(YgService.getCurrentYg().getZggs());
        hcxsd.setCreateDepartment(YgService.getCurrentYg().getZgjg());
        hcxsd.setLastUpdated(hcxsd.getDateCreated());
        hcxsd.setYxsd(yxsd);

        this.xsdDao.save(yxsd);
        this.xsdDao.save(hcxsd);

        //保存新销售单
        xsd.setXsdh(xsdBm(xsd));
        xsd.setYxsd(yxsd);
        xsd.setZt("ytj");
        xsd.setYck(false);
        xsd.setYjs(false);
        xsd.setCreateUser(YgService.getCurrentYg());
        xsd.setCreateOrgan(YgService.getCurrentYg().getZggs());
        xsd.setCreateDepartment(YgService.getCurrentYg().getZgjg());
        xsd.setDateCreated(new Date());
        xsd.setLastUpdated(xsd.getDateCreated());

        if (xsd.getXsfyList() != null && xsd.getXsfyList().size() == 0) {
            xsd.setXsfyList(null);
        } else if (xsd.getXsfyList() != null && xsd.getXsfyList().size() > 0) {
            List<Glfy> glfyList = new ArrayList<Glfy>();
            for (Glfy glfy : xsd.getXsfyList()) {
                Glfy xglfy = new Glfy();
                PropertyUtils.copyProperties(xglfy, glfy);
                xglfy.setId(null);
                glfyList.add(xglfy);
            }
            xsd.setXsfyList(glfyList);
        }

        for (int i = 0; i < list.size(); i++) {
            Xsmx xsmx = list.get(i);
            if (xsmx.getSbsl() != null && xsmx.getSbsl() != 0) {
                if (xsmx.getKh() != null) {
                    khDao.updateKhKdsl(xsmx.getKh().getId(), xsmx.getCk_sbsl());
                }
                xsmx.setYjs(false);
                xsmx.setXsjsd(null);
            } else {
                list.remove(xsmx);
                i--;
                if (list == null)
                    break;
            }
        }
        xsd.setCkr(null);
        xsd.setCksj(null);
        xsd.setXsmxList(list);
        if (xsd.getXsmxList() != null && xsd.getXsmxList().size() > 0)
            this.xsdDao.save(xsd);
    }

    @Transactional
    public void cancel(Xsd xsd) {
        xsd.setZt("ybc");
        this.xsdDao.calcKhSL(xsd, "add");
        this.xsdDao.save(xsd);
    }


    /**
     * 删除销售单信息
     *
     * @param id 销售单ID
     * @return
     */
    @Transactional
    public Xsd deleteXsd(Long id) {
        Xsd xsd = this.xsdDao.get(id);
        Xsht xsht = this.xshtDao.get(xsd.getXsht().getId());

        if (xsd.getXsjsd() != null) {
            throw new RuntimeException("禁止删除！改销售单已结算");
        }
        xsd.setLastUpdated(new Date());
        xsd.setDeleted(1);
        if (xsd.getXsmxList() != null && xsd.getXsmxList().size() != 0) {
            for (Xsmx xsmx : xsd.getXsmxList()) {
                Kh kh = khDao.get(xsmx.getKh().getId());
                kh.setYbc(0);
                khDao.save(kh);
                xsmx.setDeleted(1);
                xsmx.setLastUpdated(new Date());
                xsmxDao.save(xsmx);

            /*    for(Htmx htmx : xsht.getHtmxList()){
                    if(htmx.getWzgg().getId() == xsmx.getJtwz().getId()){
                        htmx.setYxz(0);
                        htmxDao.save(htmx);

                    }
                }*/
            }
        }
        if (xsd.getXsfyList() != null && xsd.getXsfyList().size() != 0) {
            for (Glfy glfy : xsd.getXsfyList()) {
                glfy.setDeleted(1);
                glfy.setLastUpdated(new Date());
                glfyDao.save(glfy);
            }
        }
        this.xsdDao.save(xsd);
        this.xsdDao.deleteXsmx(id);
        return xsd;
    }

    /**
     * 查询没有付款的销售单
     *
     * @param nbgsId
     * @param qyjgId
     * @return
     */
    public List<Xsd> findAllXsdBySfyfk(Long nbgsId, Long qyjgId) {
        String hql = "from Xsd where (sfyfk is null or sfyfk = 0) and XSGS_ID =? and KH_ID=? order by dateCreated  asc";
        return this.xsdDao.find(hql, nbgsId, qyjgId);
    }

    @Transactional
    public String findKhByXsd(Long xsgsId, Long sbgsId) {
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
        List<Map> khList = this.xsdDao.findKhByXsd(xsgsId, sbgsId);
        String khJson = gson.toJson(khList);
        return khJson;
    }

    /**
     * 根据Id查询客户纳税号
     *
     * @param xsgsId
     * @param
     * @return
     */
    @Transactional
    public String findKhById(Long xsgsId) {
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
        List<Map> khList = this.xsdDao.findKhById(xsgsId);
        String khJson = gson.toJson(khList);
        return khJson;
    }

    /**
     * 根据接口传过来的字符串json取值生成销售单
     */
    @Transactional(propagation = Propagation.SUPPORTS)
    public void createXsdFromJson(String jiekouStr) {
        Gson gson = new Gson();
        Map<String, Object> map = gson.fromJson(jiekouStr, new TypeToken<Map<String, Object>>() {
        }.getType());
        if (CollectionUtils.isEmpty((List) map.get("contracts"))) {
            throw new RuntimeException("没有订单信息");
        }
        List<Map> contracts = (List<Map>) map.get("contracts");
        for (Map item : contracts) {
            try {
                createXsdFromMap(item);

            } catch (Exception e) {
                e.printStackTrace();
                String order_id = item.get("order_id").toString();
                List<Dfkxsd> dfkxsdList = queryContractDao.findByProperty("orderId", Long.valueOf(order_id), null);
                for (Dfkxsd dfkxsd : dfkxsdList) {
                    dfkxsd.setLastUpdated(new Date());
                    if (e.getMessage().equals("挂单资源为自由物资"))
                        dfkxsd.setDeleted(1);
                    dfkxsd.setMessage(e.getMessage());
                    queryContractDao.save(dfkxsd);
                }

            }
        }
    }

    @Transactional(propagation = Propagation.SUPPORTS)
    public void createXsdFromMap(Map<String, Object> map) {
        List<Map> mxList = (ArrayList<Map>) map.get("goodses");
        //客户
        Gsjg kh = gsjgDao.findGsjgByCode(map.get("buyer_code").toString());
        //申报公司
        Gsjg seller = gsjgDao.findGsjgByCode(map.get("seller_code").toString());

        Boolean flag;

        flag = seller.className().equalsIgnoreCase("nbgs");

        //仓库
        Ck ck = ckDao.findByMc(mxList.get(0).get("warehouse_name").toString());
        String orderId = map.get("order_id").toString();
        //订单（合同） 生成时间，时间毫秒数,如果要获取北京时间的话,需要+8小时
        String add_time = map.get("add_time").toString();
        //发货时间，时间毫秒数,如果要获取北京时间的话,需要+8小时
        String ship_time = map.get("ship_time") == null ? null : map.get("ship_time").toString();
        //交易完成时间，时间毫秒数,如果要获取北京时间的话,需要+8小时
        String finished_time = map.get("finished_time") == null ? null : map.get("finished_time").toString();
        Xsd xsd = new Xsd();
        xsd.setXsdh(bmService.getXsdbm("htxs"));
        xsd.setXslx("htxs");
        xsd.setKh(kh);
        xsd.setThck(ck);
        xsd.setOrderId(orderId);
//      xsd.setOrderCode(orderCode);
        xsd.setFhsj(new Date());
        xsd.setSxsj(new Date(Long.valueOf(add_time + "000") + 8 * 60 * 60 * 1000));
        xsd.setDateCreated(new Date());
        xsd.setLastUpdated(new Date());
        if (StringUtils.isNotEmpty(ship_time) && !ship_time.equals("0")) {
            xsd.setFhsj(new Date(Long.valueOf(ship_time + "000") + 8 * 60 * 60 * 1000));
        }
        if (StringUtils.isNotEmpty(finished_time) && !finished_time.equals("0")) {
            xsd.setJhsj(new Date(Long.valueOf(finished_time + "000") + 8 * 60 * 60 * 1000));
        }
        xsd.setFyzr(sjzdzService.findSjzdzByMc("自提"));
        xsd.setSbgs(seller);
        xsd.setXsgs(seller);
        xsd.setSl(17.0);
        if (flag) {
            xsd.setFhfs("transfer");
            xsd.setZt("ybc");
        } else {
            xsd.setFhfs("self");
            xsd.setZt("ytj");
        }
        xsd.setCreateOrgan(seller);
        List<Xsmx> xsmxList = new ArrayList<Xsmx>();
        for (int i = 0; i < mxList.size(); i++) {
            String name = mxList.get(i).get("goods_name").toString();
            String ggxh = mxList.get(i).get("spec").toString();
            String cz = mxList.get(i).get("metarial").toString();
            String price = mxList.get(i).get("real_price").toString();
            String js = mxList.get(i).get("quantity").toString();
            String measure = mxList.get(i).get("measure").toString();
            String bz = mxList.get(i).get("comment").toString();
            if (mxList.get(i).get("hang_resource_number") == null) {
                throw new RuntimeException("挂单资源编号:null");
            }
            String cgdUseCode = mxList.get(i).get("hang_resource_number").toString();
            String[] strings = cgdUseCode.split("-");
            if (strings.length >= 3) {
                String cgdh = strings[0] + "-" + strings[1];  //CGRK-13123000001
                String pxh = strings[2];
                Kh createKh = this.cgdmxItertorFindKh(cgdh, pxh);
                Gg gg = ggDao.findByPro(name, ggxh, cz);
                if (gg == null) {
                    throw new RuntimeException("没有找到物资");
                }
                Xsmx xsmx = new Xsmx();
                xsmx.setKh(createKh);
                xsd.setLj(createKh.getCgd().getLj());
                xsmx.setJtwz(gg);
                xsmx.setHang_resource_number(cgdUseCode);
                xsmx.setJzfs(sjzdzService.findSjzdzByMc("理重"));
                xsmx.setJs(Integer.valueOf(js));
                xsmx.setSbsl(Math.round(Double.valueOf(js) * Double.valueOf(measure) * 10000) / 10000.0);
                xsmx.setHsj(Double.valueOf(price));
                xsmx.setBhsj((Math.round((Double.valueOf(price) / 1.17) * 10000) / 10000.0));
                xsmx.setXscb((Math.round((Double.valueOf(price) / 1.17) * 10000) / 10000.0));
                xsmx.setBz(bz);
                Map<String, Object> shj = shjDao.calculate(createKh.getId(), xsd.getDateCreated());
                if (flag) {
                    xsmx.setYhjg(((BigDecimal) shj.get("yhjg")).doubleValue());
                }
                xsmxList.add(xsmx);
            } else {
                throw new RuntimeException("挂单资源为自由物资");
            }
        }
        xsd.setXsmxList(xsmxList);
        xsdDao.save(xsd);
        this.createCgdFromXsd(xsd);//根据销售单生成采购单

        //删除已生成销售单的代付款销售单
        List<Dfkxsd> dfkxsdList = queryContractDao.findByProperty("orderId", Long.valueOf(orderId), null);
        for (Dfkxsd dfkxsd : dfkxsdList) {
            dfkxsd.setDeleted(1);
            dfkxsd.setLastUpdated(new Date());
            dfkxsd.setMessage("");
            queryContractDao.save(dfkxsd);
        }

//        if (flag) {
//            // 判断 控货价 × 质物总数量 × 质押率 ＋ 监管账户余额 ≥ 控货值
//            Boolean bool = xsdControlPd(xsd);
//            if (bool) {
//                //发送出货指令
//                Gson gson = new Gson();
//                String json = createGoodsOrderJson(xsd);
//                String result = this.webserviceTransService.transXsdGdWebServiceArgs(xsd.getSbgs().getBm(), json);
//                if (result != null) {
//                    List<Map<String, Object>> resultList = gson.fromJson(result, new TypeToken<List<Map<String, Object>>>() {
//                    }.getType());
//                    if (resultList != null) {
//                        if (resultList.get(0).get("code").equals("0")) {
//                            xsd.setZt("ytj");
//                        }
//                    }
//                }
//            }
//        }
//        createXsdFromInterfaceXsd(xsd);
    }

    @Transactional(propagation = Propagation.SUPPORTS)
    public void createXsdFromInterfaceXsd(Xsd xsd) {
        Xsd newXsd = new Xsd();
        newXsd = (Xsd) ReflectionUtils.getInstance(newXsd, xsd);
        newXsd.setId(null);
        newXsd.setXsdh(bmService.getXsdbm("htxs"));
        newXsd.setBcxsd(xsd);
        newXsd.setXsgs(gsjgDao.get(24l));
        newXsd.setSbgs(gsjgDao.get(24l));
        newXsd.setKh(xsd.getXsgs());
        newXsd.setZt("ybc");
        List<Xsmx> xsmxList = new ArrayList<Xsmx>();
        for (Xsmx xsmx : newXsd.getXsmxList()) {
            Xsmx newXsmx = new Xsmx();
            newXsmx = (Xsmx) ReflectionUtils.getInstance(newXsmx, xsmx);
            newXsmx.setId(null);
            Gd gd = gdDao.findGdByCode(xsmx.getHang_resource_number().substring(0, xsmx.getHang_resource_number().lastIndexOf("_")));
            Double hsj = Double.parseDouble(gd.getPrice());
            newXsmx.setHsj(hsj);
            newXsmx.setBhsj((Math.round((hsj / 1.17) * 10000) / 10000.0));
            xsmxList.add(newXsmx);
        }
        newXsd.setXsmxList(xsmxList);
        xsdDao.save(newXsd);


    }

    public Kh cgdmxItertorFindKh(String cgdh, String pxh) {
        Cgd cgd = cgdDao.findCgdFindCgdh(cgdh);
        Kh nkh = new Kh();
        for (Cgdmx cgdmx : cgd.getCgdmxList()) {
            for (Kh kh : cgdmx.getKhList()) {
                if (pxh.endsWith(kh.getPxh().toString())) {
                    nkh = kh;
                }
            }
        }
        return nkh;
    }

    /**
     * 将物资拼成json传到接口
     *
     * @return
     */
    public String createJsonToInterFace(String mark, List<Kh> khList) {
        SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd");
        StringBuffer json = new StringBuffer();
        json.append("[");
        for (int i = 0; i < khList.size(); i++) {
            String str1 = StringUtils.EMPTY;
            Cgd cgd = khList.get(i).getCgd();
            String timesDivision = this.getTimeDivision();
            String resource_serial_number = cgd.getCgdh() + "-" + khList.get(i).getPxh() + "-" + timesDivision; //挂单资源唯一号
            String stander_name = "";
            String cate = "";
            String material = "";
            String spec = "";
            String weight = "";
            String weight_count = "";
            String brand = "";
            String measure_count = "";
            String total_measure = "";
            String warehouse = "";
            String market_price = "";
            String measure = "";
            String price = "";
            String preferential_price = "";
            String user_id = "";
            String production_date = "";
            try {
                stander_name = (khList.get(i).getJtwz() == null ? "" : khList.get(i).getJtwz().getName()); //品名
                material = (khList.get(i).getJtwz() == null ? "" : khList.get(i).getJtwz().getCz());//材质
                spec = (khList.get(i).getJtwz() == null ? "" : khList.get(i).getJtwz().getGgxh());//规格
                cate = (khList.get(i).getJtwz() == null ? "" : khList.get(i).getJtwz().getPm().getRjwzbm().getName());//产品分类，如建筑钢材/热轧带肋钢筋
                if (khList.get(i).getJtwz() != null) {
                    weight = (khList.get(i).getJtwz().getDw() != null && khList.get(i).getJtwz().getDw().equals("t")) ? "吨" : khList.get(i).getJtwz().getDw() == null ? "" : khList.get(i).getJtwz().getDw(); //单位
                    weight_count = StringUtils.isEmpty(khList.get(i).getJtwz().getSldw()) ? "件" : khList.get(i).getJtwz().getSldw(); //数量单位
                } else {
                    weight = "吨"; //单位
                    weight_count = "件"; //数量单位
                }
                if (khList.get(i).getKhdj() == null) {
                    Map djMap = this.shjDao.calculate(khList.get(i).getId());
                    market_price = djMap.get("hsj").toString(); //挂牌价
                    preferential_price = djMap.get("hsj").toString();//优惠价
                    price = djMap.get("hsj").toString();//销售底价，等同挂牌价
                } else {
                    market_price = khList.get(i).getKhdj().toString(); //挂牌价
                    preferential_price = (khList.get(i).getKhdj() == null ? "0" : khList.get(i).getKhdj().toString());//优惠价
                    price = khList.get(i).getKhdj().toString();//销售底价，等同挂牌价
                }

                brand = (khList.get(i).getCd() == null ? "" : khList.get(i).getCd().getZ());//产地
                measure_count = khList.get(i).getLsjs() == null ? "1" : khList.get(i).getLsjs().toString();
                total_measure = khList.get(i).getLssl().toString();
                warehouse = (khList.get(i).getCk() == null ? "" : khList.get(i).getCk().getMc());//仓库
//                market_price = (khList.get(i).getKhdj() == null ? "0" : khList.get(i).getKhdj().toString()); //挂牌价
                measure = khList.get(i).getJz().toString();//件重
//                price = (khList.get(i).getKhdj() == null ? "0" : khList.get(i).getKhdj().toString());//销售底价，等同挂牌价
//                preferential_price = (khList.get(i).getKhdj() == null ? "0" : khList.get(i).getKhdj().toString());//优惠价，等同挂牌价
                user_id = khList.get(i).getSbgs().getBm();
                production_date = ft.format(new Date());
                str1 = "{\"resource_serial_number\":\"" + resource_serial_number + "\",\"stander_name\":\"" + stander_name + "\",\"cate\":\"" + cate + "\",\"material\":\"" + material + "\",\"spec\":\"" + spec + "\",\"brand\":\"" + brand + "\",\"warehouse\":\"" + warehouse + "\",\"warehouse_code\":\"\",\"calculate_type\":\"\",\"measure_count\":\"" + measure_count + "\",\"unit\":\"" + weight_count + "\",\"measure\":\"" + measure + "\",\"total_measure\":\"" + total_measure + "\",\"weight\":\"" + weight + "\",\"min_sale\":\"\",\"market_price\":\"" + market_price + "\",\"price\":\"" + price + "\",\"preferential_price\":\"" + preferential_price + "\",\"user_id\":\"" + user_id + "\",\"production_date\":\"" + production_date + "\",\"standard\":\"\",\"region\":\"昆明\"},";
                json.append(str1);
                this.saveGd(mark, khList.get(i), resource_serial_number, stander_name, cate, material, spec, brand, measure_count, total_measure, warehouse, market_price, measure, price, preferential_price, user_id, production_date);
            } catch (Exception e) {
//                e.printStackTrace();
            }
        }
        if (json.length() > 1) {
            json = json.deleteCharAt(json.length() - 1);
        }
        json.append("]");
        return json.toString();
    }

    public String getTimeDivision() {
        return String.valueOf(new Date().getTime());
    }


    private void saveGd(String mark, Kh kh, String resource_serial_number, String stander_name, String cate, String material, String spec, String brand, String measure_count, String total_measure, String warehouse, String market_price, String measure, String price, String preferential_price, String user_id, String production_date) {
        Gd gd = new Gd();
        //   gd.setKh(kh);
//        gd.setResource_serial_number(resource_serial_number);
//        gd.setStander_name(stander_name);
//        gd.setCate(cate);
//        gd.setMaterial(material);
//        gd.setSpec(spec);
//        gd.setBrand(brand);
//        gd.setMeasure_count(measure_count);
//        gd.setTotal_measure(total_measure);
//        gd.setWarehouse(warehouse);
//        gd.setMarket_price(market_price);
//        gd.setMeasure(measure);
//        gd.setPrice(price);
//        gd.setPreferential_price(preferential_price);
//        gd.setUser_id(user_id);
//        gd.setProduction_date(production_date);
//        gd.setLastUpdated(new Date());
//        if ("all".equals(mark)) {
//            gd.setCreateOrgan(kh.getCggs());
//        } else {
//            gd.setCreateUser(YgService.getCurrentYg());
//            gd.setCreateOrgan(YgService.getCurrentYg().getZggs());
//            gd.setCreateDepartment(YgService.getCurrentYg().getZgjg());
//        }
//        gdDao.save(gd);
    }

    /**
     * 查询销售单已经付款的记录总和
     *
     * @param xsdId
     * @return
     */

    public Double getAllYfk(Long xsdId) {
        String sql = "select nvl(sum(fpje),0) from t_biz_zjfpmx where xsd_id=?";
        List list = this.zjfpmxDao.findBySQL(sql, xsdId);
        return Double.valueOf(list.get(0).toString());
    }

    /**
     * 更新是否已经完成付款，并保持付款记录
     *
     * @param xsdId
     * @param sfyfk
     * @param Fpje
     */
    @Transactional
    public void saveInfo(Long xsdId, String sfyfk, Double Fpje) {
        Xsd xsdTemp = this.xsdDao.get(xsdId);
        if (sfyfk.equals("1")) {
            xsdTemp.setSfyfk(sfyfk);
            xsdTemp.setYfksj(new Date());
        }
        this.xsdDao.save(xsdTemp);

        Zjfpmx zjfpmxTemp = new Zjfpmx();
        zjfpmxTemp.setNbgs(xsdTemp.getXsgs());
        if (xsdTemp.getKh() != null)
            zjfpmxTemp.setQyjg((Qyjg) xsdTemp.getKh());
        zjfpmxTemp.setXsd(xsdTemp);
        zjfpmxTemp.setFpje(Fpje);
        zjfpmxTemp.setDateCreated(new Date());
        this.zjfpmxDao.save(zjfpmxTemp);

    }


    @Transactional
    public void xsdtzApply(Long xsdId) {
        Xsd xsd = this.xsdDao.get(xsdId);
        xsd.setTzsqzt("ysq");
        xsd.setLastUpdated(new Date());
        this.xsdDao.save(xsd);
    }

    @Transactional
    public void xsdtzCancel(Long xsdId) {
        Xsd xsd = this.xsdDao.get(xsdId);
        xsd.setTzsqzt("wsq");
        xsd.setLastUpdated(new Date());
        this.xsdDao.save(xsd);
    }

    @Transactional
    public void xsdtzExamine(Long xsdId) {
        Xsd xsd = this.xsdDao.get(xsdId);
        xsd.setTzsqzt("ysp");
        xsd.setLastUpdated(new Date());
        this.xsdDao.save(xsd);
    }

    @Transactional
    public void saveXsdPrintElements(Long xsdId, String zh, String lsh, String thrs, String jbr, String sfzhm, String cars, String year, String month, String day) {
        Xsd xsd = this.xsdDao.get(xsdId);
        xsd.setZh(zh);
        xsd.setLsh(lsh);
        xsd.setThrs(thrs);
        xsd.setJbr(jbr);
        xsd.setSfzhm(sfzhm);
        xsd.setCars(cars);
        xsd.setYear(year);
        xsd.setMonth(month);
        xsd.setDay(day);
        this.xsdDao.save(xsd);
    }

    /**
     * 生成放货通知的接口参数
     *
     * @param xsd
     * @return
     */
    private String createGoodsNoticeJson(Xsd xsd, String type) {
        StringBuffer sb = new StringBuffer();
        sb.append("{\"scontractBillcode\":\"").append(xsd.getXsdh()).append("\",");
        sb.append("\"billBillcode\":\"").append(xsd.getXsdh()).append("\",");
        if (type.equals("self")) {
            sb.append("\"buyerCompany\":\"").append(xsd.getKh().getQc()).append("\",");
        } else {
            sb.append("\"buyerCompany\":\"").append(xsd.getSbgs().getQc()).append("\",");
        }

        sb.append("\"reportCompany\":\"").append(xsd.getKh().getQc()).append("\",");
        sb.append("\"goodsNum\":\":goodsNum\",");
        sb.append("\"goodsWeight\":\":goodsWeight\",");
        sb.append("\"scontractPumode\":\"").append(type).append("\",");
        sb.append("\"billType\":\"lading\",");
        sb.append("\"status\":\"0\",");
        sb.append("\"transferSign\":\"1\",");
        sb.append("\"materialType\":\"1\",");
        sb.append("\"memberCode\":\"").append(xsd.getSbgs().getBm()).append("\",\"saleBillCodeViewVoList\":[");
        Integer js = 0;
        Double sl = 0.0;
        for (Xsmx xsmx : xsd.getXsmxList()) {
            sb.append("{\"name\":\"").append(xsmx.getJtwz().getName()).append("\",");
            sb.append("\"quality\":\"").append(xsmx.getJtwz().getCz()).append("\",");
            sb.append("\"standard\":\"").append(xsmx.getJtwz().getGgxh()).append("\",");
            if (null != xsmx.getKh() && null != xsmx.getKh().getCd() && StringUtils.isNotBlank(xsmx.getKh().getCd().getZ())) {
                sb.append("\"field\":\"").append(xsmx.getKh().getCd().getZ()).append("\",");
            } else {
                sb.append("\"field\":\"").append("").append("\",");
            }

            if (null != xsmx.getKh() && null != xsmx.getKh().getCk() && StringUtils.isNotBlank(xsmx.getKh().getCk().getMc())) {
                sb.append("\"warehouse\":\"").append(xsmx.getKh().getCk().getMc()).append("\",");
            } else {
                sb.append("\"warehouse\":\"").append("").append("\",");
            }
            sb.append("\"carNo\":\"").append(xsmx.getKh().getCarNo()).append("\",");
            sb.append("\"sellNo\":\"").append(xsmx.getKh().getXsxt_htbm()).append("\",");
            sb.append("\"sellSubNo\":\"").append(xsmx.getKh().getXsxt_xsdh()).append("\",");
            sb.append("\"resource_serial_number_1\":\"").append(xsmx.getKh().getResource_serial_number_1()).append("\",");
            sb.append("\"bindNo\":\"").append(xsmx.getKh().getBindNo()).append("\",");
            sb.append("\"numberUnit\":\"").append("件").append("\",");
            sb.append("\"number\":\"").append(xsmx.getJs() == null ? 1 : xsmx.getJs()).append("\",");
            sb.append("\"weightUnit \":\"").append(xsmx.getJtwz().getDw()).append("\",");
            sb.append("\"weight\":\"").append(xsmx.getKh().getSl()).append("\"},");
            js += xsmx.getJs() == null ? 1 : xsmx.getJs();
            sl += xsmx.getSbsl();
        }
        sb = sb.deleteCharAt(sb.length() - 1);
        sb.append("]}");
        String json = sb.toString().replaceAll(":goodsNum", js.toString());
        json = json.replaceAll(":goodsWeight", sl.toString());
        return json;
    }

    /**
     * 生成放货指令的接口参数
     *
     * @param xsd
     * @return
     */
    private String createGoodsOrderJson(Xsd xsd) {
        StringBuffer sb = new StringBuffer();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        sb.append("[{\"contractid\":\"").append(xsd.getOrderId()).append("\",");
        sb.append("\"release_cargo_num\":\"").append(xsd.getXsdh()).append("\",");
        sb.append("\"valid_date\":\"").append(sdf.format(new Date())).append("\",");
        sb.append("\"remark\":\"\",\"goods\":[");

        for (Xsmx xsmx : xsd.getXsmxList()) {
            sb.append("{\"stander_name\":\"").append(xsmx.getJtwz().getName()).append("\",");
            sb.append("\"material\":\"").append(xsmx.getJtwz().getCz()).append("\",");
            sb.append("\"spec\":\"").append(xsmx.getJtwz().getGgxh()).append("\",");
            sb.append("\"brand\":\"").append(xsmx.getKh().getCd().getZ()).append("\",");
            if (null != xsd.getThck()) {
                sb.append("\"warehouse\":\"").append(xsd.getThck().getMc()).append("\",");
                sb.append("\"warehouse_code\":\"").append(xsd.getThck().getBh()).append("\",");
            } else {
                sb.append("\"warehouse\":\"").append("").append("\",");
                sb.append("\"warehouse_code\":\"").append("").append("\",");
            }

            sb.append("\"bale_code\":\"\",");
            sb.append("\"measure_count\":\"").append(xsmx.getJs() == null ? 1 : xsmx.getJs()).append("\",");
            sb.append("\"weight\":\"").append(xsmx.getSbsl()).append("\",");
            sb.append("\"batch_code\":\"\",");
            sb.append("\"production_date\":\"\"},");
        }
        sb = sb.deleteCharAt(sb.length() - 1);
        sb.append("]}]");
        return sb.toString();
    }


    public Boolean getXsdControlPd(Xsd xsd) {
        return xsdControlPd(xsd);
    }

    @Transactional
    public Map<String, String> jzXsd(Xsd xsd) {
        Map<String, String> map = new HashMap<String, String>();
        Boolean bool = false;
        String status = "100";
        String message = "初始化";
        if (null != xsd) {
            for (Xsmx xsmx : xsd.getXsmxList()) {
                Zyf zyf = xsmx.getKh().getCgd().getCght().getZyf();
                if (null != zyf) {
                    // 控货价
                    Khjwh khjwh = this.khjwhDao.findKhjByPmId(xsmx.getJtwz().getPm().getId());
                    Double khj = 0.0;
                    if (null == khjwh) {
                        bool = false;
                        status = "300";
                        message = "品名：" + xsmx.getJtwz().getPm().getName() + "，控货价为空，请维护控货价！";
                        break;
                    } else {
                        khj = khjwh.getKhj();
                    }
                    Double zwzsl = xsmx.getKh().getSl(); //  质物总数量
                    Double zyl = xsmx.getKh().getCgd().getCght().getZyf().getZyl(); // 质押率
                    if (null == zyl) {
                        bool = false;
                        status = "300";
                        message = "质押方：" + zyf.getQc() + "，质押率为空，请维护质押方质押率！";
                        break;
                    }
                    // 监管账户余额
                    List<Ejzh> ejzhList = this.ejzhDao.findEjzhByKhAndNbgsId(xsd.getKh().getId(), xsd.getSbgs().getId());
                    Double jgzhye = 0.0;
                    if (null != ejzhList && ejzhList.size() > 0) {
                        Ejzh ejzh = ejzhList.get(0);
                        jgzhye = ejzh.getKyye() + ejzh.getBzj();
                    } else {
                        bool = false;
                        status = "300";
                        message = "质押方：" + zyf.getQc() + "，监管账户为空，请维护监管账户余额！";
                        break;
                    }
                    // 最低控货值
                    Zdkhz zdkhz = this.zdkhzDao.findByZyfId(xsmx.getKh().getCgd().getCght().getZyf().getId());
                    Double khz = 0.0;
                    if (null == zdkhz) {
                        bool = false;
                        status = "300";
                        message = "质押方：" + zyf.getQc() + "，最低控货值为空，请维护最低控货值！";
                        break;
                    } else {
                        khz = zdkhz.getZdkhz();
                    }
                    Double c = khj * zwzsl * zyl + jgzhye;
                    if (c >= khz) {
                        bool = true;
                        status = "200";
                        message = "该销售单解质成功！";
                    } else {
                        bool = false;
                        status = "300";
                        DecimalFormat df = new DecimalFormat("#,###.####");
                        String cStr = df.format(Double.parseDouble(c.toString()));
                        String khzStr = df.format(Double.parseDouble(khz.toString()));
                        message = "材质明细（" + xsmx.getJtwz().getPm().getName() + "），控货价×质物总重量×质押率＋监管账户余额（" + cStr + "）>= 控货值（"
                                + khzStr + "），不满足，不能进行解质！";
                        break;
                    }
                } else {
                    bool = true;
                }
            }
        } else {
            bool = false;
            status = "300";
            message = "没有查询到销售单信息！";
        }
        map.put("status", status);
        map.put("message", message);
        if (bool) {
            xsd.setZt("ybc");
            this.xsdDao.save(xsd);
        }
        return map;
    }

    @Transactional
    private Boolean xsdControlPd(Xsd xsd) {
        Boolean bool = false;
        if (null != xsd) {
            for (Xsmx xsmx : xsd.getXsmxList()) {
                Zyf zyf = xsmx.getKh().getCgd().getCght().getZyf();
                if (null != zyf) {
                    // 控货价
                    Khjwh khjwh = this.khjwhDao.findKhjByPmId(xsmx.getJtwz().getPm().getId());
                    Double khj = 0.0;
                    if (null == khjwh) {
                        bool = false;
                        break;
                    } else {
                        khj = khjwh.getKhj();
                    }
                    Double zwzsl = xsmx.getKh().getSl(); //  质物总数量
                    Double zyl = xsmx.getKh().getCgd().getCght().getZyf().getZyl(); // 质押率
                    if (null == zyl) {
                        bool = false;
                        break;
                    }
                    // 监管账户余额
                    List<Ejzh> ejzhList = this.ejzhDao.findEjzhByKhAndNbgsId(xsd.getKh().getId(), xsd.getSbgs().getId());
                    Double jgzhye = 0.0;
                    if (null != ejzhList && ejzhList.size() > 0) {
                        Ejzh ejzh = ejzhList.get(0);
                        jgzhye = ejzh.getKyye() + ejzh.getBzj();
                    } else {
                        bool = false;
                        break;
                    }
                    // 最低控货值
                    Zdkhz zdkhz = this.zdkhzDao.findByZyfId(xsmx.getKh().getCgd().getCght().getZyf().getId());
                    Double khz = 0.0;
                    if (null == zdkhz) {
                        bool = false;
                        break;
                    } else {
                        khz = zdkhz.getZdkhz();
                    }
                    Double c = khj * zwzsl * zyl + jgzhye;
                    if (c >= khz) {
                        bool = true;
                    } else {
                        bool = false;
                        break;
                    }
                } else {
                    bool = true;
                }
            }
        } else {
            bool = true;
        }
        if (!bool) {
            xsd.setZt("yzy");
            this.xsdDao.save(xsd);
        }
        return bool;
    }

    @Transactional
    public String findXsdSkList(Xsd xsd, Long gldwId, Integer type, String htmx, int pageNo, int pageSize) {
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
        Page page = null;
        // 判断是非计划现货(线上) 0，还是金融物流（线下） 1
        Integer fplx = 1;
        if (htmx.equals("xsms")) {
            fplx = 0;
        }
        if (type.equals(0)) {
            page = skshDao.findXsdSkList(xsd, gldwId, fplx, pageNo, pageSize);
        } else if (type.equals(1)) {
            page = skshDao.findProrateSkList(gldwId, fplx, pageNo, pageSize);
        } else {
            page = hthkDao.findNoBindSkList(xsd.getXsht().getZddhcght().getId(), pageNo, pageSize);
        }
        return "{\"total\":" + page.getTotalCount() + ",\"rows\":" + gson.toJson(page.getResult()) + "}";
    }


    /**
     * 挂款不通过，进行回退处理
     *
     * @param bool
     * @param xsdId
     */
    @Transactional
    public void gksh_saveItem(Boolean bool, Long xsdId) {
        if (bool) {
            Xsd xsd = this.xsdDao.get(xsdId);
            xsd.setZt("ytj");
            xsd.setGksh("1");
            xsd.setGkshr(YgService.getCurrentYg());
            xsd.setGkshsj(new Date());
            this.xsdDao.save(xsd);
        } else {
            Xsd xsd = this.xsdDao.get(xsdId);
            if (xsd.getXsht().getZddhcght().getBzjfs() == 0) {
                // 计费明细
                List<Jfmx> jfmxList = this.jfmxDao.findJfmxByXsdId(xsdId);
                if (null != jfmxList && jfmxList.size() > 0) {
                    for (Jfmx jfmx : jfmxList) {
                        Sfk sfk = this.skshDao.get(jfmx.getSfk().getId());
                        sfk.setYe(CalcUtils.round(sfk.getYe() + jfmx.getZjfpje() + jfmx.getTxje(), 2));
                        this.skshDao.save(sfk);
                        // 保存副本
                        Jfmxdelete jfmxdelete = new Jfmxdelete();
                        jfmxdelete.setTxje(jfmx.getTxje());
                        jfmxdelete.setJsd(jfmx.getJsd());
                        jfmxdelete.setCreated_date(new Date());
                        jfmxdelete.setDlfje(jfmx.getDlfje());
                        jfmxdelete.setGhje(jfmx.getGhje());
                        jfmxdelete.setHsj(jfmx.getHsj());
                        jfmxdelete.setJszyts(jfmx.getJszyts());
                        jfmxdelete.setKh(jfmx.getKh());
                        jfmxdelete.setKhfksj(jfmx.getKhfksj());
                        jfmxdelete.setScr(YgService.getCurrentYg());
                        jfmxdelete.setSfjs(jfmx.getSfjs());
                        jfmxdelete.setSfk(jfmx.getSfk());
                        jfmxdelete.setShsj(jfmx.getShsj());
                        jfmxdelete.setSjjsj(jfmx.getSjjsj());
                        jfmxdelete.setTzfksj(jfmx.getTzfksj());
                        jfmxdelete.setXsht(jfmx.getXsht());
                        jfmxdelete.setXsmx(jfmx.getXsmx());
                        jfmxdelete.setZjfpje(jfmx.getZjfpje());
                        jfmxdelete.setXsd(jfmx.getXsd());
                        jfmxdelete.setZjzyf(jfmx.getYhje());
                        jfmxdelete.setZl(jfmx.getZl());
                        jfmxdelete.setSjzyts(jfmx.getSjzyts());
                        this.jfmxDeteleDao.save(jfmxdelete);
                        this.jfmxDao.delete(jfmx.getId());
                    }
                }
                // 代理费
                List<Dlf> dlfList = this.dlfDao.findDlfByXsdId(xsdId);
                if (null != dlfList && dlfList.size() > 0) {
                    for (Dlf dlf : dlfList) {
                        Sfk sfk = this.skshDao.get(dlf.getSfkId());
                        sfk.setYe(CalcUtils.round(sfk.getYe() + dlf.getDlf(), 2));
                        this.skshDao.save(sfk);
                        dlf.setDeleted(1);
                        this.dlfDao.save(dlf);
                    }
                }

            } else if (xsd.getXsht().getZddhcght().getBzjfs() == 1) {
                // 预保存按比例释放扣款
                List<Ablbzjgk> ablbzjgkList = this.ablbzjshDao.findAllAblbzjgk(xsd);
                if (null != ablbzjgkList && ablbzjgkList.size() > 0) {
                    for (Ablbzjgk ablbzjgk : ablbzjgkList) {
                        Sfk sfk = this.skshDao.get(ablbzjgk.getSfk_id());
                        sfk.setYe(CalcUtils.round(sfk.getYe() + ablbzjgk.getJe(), 2));
                        this.skshDao.save(sfk);
                        ablbzjgk.setDeleted(1);
                        ablbzjgk.setBz(1l);
                        this.ablbzjshDao.save(ablbzjgk);
                    }
                }
            } else {
                // 预保存无保证金扣款
                List<Wbzjgk> wbzjgksList = this.wbzjshDao.findAllNoBondGk(xsd);
                if (null != wbzjgksList && wbzjgksList.size() > 0) {
                    for (Wbzjgk wbzjgk : wbzjgksList) {
                        Hthk hthk = this.hthkDao.findAllHthk(xsd.getXsht().getZddhcght(), wbzjgk.getSfk_id());
                        hthk.setYe(CalcUtils.round(hthk.getYe() + wbzjgk.getJe(), 2));
                        this.hthkDao.save(hthk);
                        wbzjgk.setDeleted(1);
                        wbzjgk.setBz(1l);
                        this.wbzjshDao.save(wbzjgk);
                    }
                }
            }
//            xsd.setZt("ysh");
            xsd.setZt("ybc");
            xsd.setGksh("0");
            xsd.setGkshr(YgService.getCurrentYg());
            xsd.setGkshsj(new Date());
            this.xsdDao.save(xsd);
        }

    }


    public Boolean checkLastCondition(Long xsdId) {
        Xsd xsdTemp = this.xsdDao.get(xsdId);
        Cght cght = xsdTemp.getXsht().getZddhcght();
        if (cght.getLastsh() == 1) {
            return false;
        } else {
            List list = this.xsdDao.findSurplusKh(cght.getId(), xsdTemp.getXsmxList());
            if (null != list && list.size() > 0) {
                return false;
            }
        }
        return true;
    }


    /**
     * 配款出库后修改材料状态
     *
     * @param xsd
     */
    public void updateClxxZtForXsmx(Xsd xsd) {
        for (Xsmx xsmx : xsd.getXsmxList()) {
            Clxx clxx = clxxDao.findClxxByClh(xsmx.getBindNo());
            if (null != clxx && clxx.getId() != null) {
                clxx.setZt("2");//出库
                clxxDao.save(clxx);
            }
        }
    }

    public Map findXsdTzdInfo(Long khId) {
        return this.xsdDao.findXsdTzdInfo(khId);
    }

    @Autowired
    public void setCgdDao(CgdDao cgdDao) {
        this.cgdDao = cgdDao;
    }

    @Autowired
    public void setKhDao(KhDao khDao) {
        this.khDao = khDao;
    }

    @Autowired
    public void setXsdDao(XsdDao xsdDao) {
        this.xsdDao = xsdDao;
    }

    @Autowired
    public void setGlfyDao(GlfyDao glfyDao) {
        this.glfyDao = glfyDao;
    }

    @Autowired
    public void setSjzdzService(SjzdzService sjzdzService) {
        this.sjzdzService = sjzdzService;
    }

    @Autowired
    public void setCkDao(CkDao ckDao) {
        this.ckDao = ckDao;
    }


    @Autowired
    public void setSjzdzDao(SjzdzDao sjzdzDao) {
        this.sjzdzDao = sjzdzDao;
    }

    @Autowired
    public void setZjfpmxDao(ZjfpmxDao zjfpmxDao) {
        this.zjfpmxDao = zjfpmxDao;
    }

    @Autowired
    public void setXsmxDao(XsmxDao xsmxDao) {
        this.xsmxDao = xsmxDao;
    }

    @Autowired
    public void setXsjsdDao(XsjsdDao xsjsdDao) {
        this.xsjsdDao = xsjsdDao;
    }

    @Autowired
    public void setXsjsdmxDao(XsjsdmxDao xsjsdmxDao) {
        this.xsjsdmxDao = xsjsdmxDao;
    }

    @Autowired
    public void setZjbcdDao(ZjbcdDao zjbcdDao) {
        this.zjbcdDao = zjbcdDao;
    }

    @Autowired
    public void setZjbcdRzDao(ZjbcdRzDao zjbcdRzDao) {
        this.zjbcdRzDao = zjbcdRzDao;
    }

    @Autowired
    public void setGsjgDao(GsjgDao gsjgDao) {
        this.gsjgDao = gsjgDao;
    }

    @Autowired
    public void setGgDao(GgDao ggDao) {
        this.ggDao = ggDao;
    }

    @Autowired
    public void setGdDao(GdDao gdDao) {
        this.gdDao = gdDao;
    }


    @Autowired
    public void setWebserviceTransService(WebserviceTransService webserviceTransService) {
        this.webserviceTransService = webserviceTransService;
    }

    @Autowired
    public void setEjzhDao(EjzhDao ejzhDao) {
        this.ejzhDao = ejzhDao;
    }

    @Autowired
    public void setDfkxsdDao(DfkxsdDao dfkxsdDao) {
        this.dfkxsdDao = dfkxsdDao;
    }

    @Autowired
    public void setBmService(BmService bmService) {
        this.bmService = bmService;
    }

    @Autowired
    public void setSkshDao(SkshDao skshDao) {
        this.skshDao = skshDao;
    }

    @Autowired
    public void setQueryContractDao(QueryContractDao queryContractDao) {
        this.queryContractDao = queryContractDao;
    }

    @Autowired
    public void setShjDao(ShjDao shjDao) {
        this.shjDao = shjDao;
    }

    @Autowired
    public void setKhjwhDao(KhjwhDao khjwhDao) {
        this.khjwhDao = khjwhDao;
    }

    @Autowired
    public void setZdkhzDao(ZdkhzDao zdkhzDao) {
        this.zdkhzDao = zdkhzDao;
    }

    @Autowired
    public void setJfmxDao(JfmxDao jfmxDao) {
        this.jfmxDao = jfmxDao;
    }

    @Autowired
    public void setJkpzDao(JkpzDao jkpzDao) {
        this.jkpzDao = jkpzDao;
    }

    @Autowired
    public void setCkshService(CkshService ckshService) {
        this.ckshService = ckshService;
    }

    @Autowired
    public void setWbzjshDao(WbzjshDao wbzjshDao) {
        this.wbzjshDao = wbzjshDao;
    }

    @Autowired
    public void setBzjDao(BzjDao bzjDao) {
        this.bzjDao = bzjDao;
    }

    @Autowired
    public void setDlfDao(DlfDao dlfDao) {
        this.dlfDao = dlfDao;
    }

    @Autowired
    public void setHthkDao(HthkDao hthkDao) {
        this.hthkDao = hthkDao;
    }

    @Autowired
    public void setAblbzjshDao(AblbzjshDao ablbzjshDao) {
        this.ablbzjshDao = ablbzjshDao;
    }

    @Autowired
    public void setJfmxDeteleDao(JfmxDeteleDao jfmxDeteleDao) {
        this.jfmxDeteleDao = jfmxDeteleDao;
    }

    @Autowired
    public void setJyddDao(JyddDao jyddDao) {
        this.jyddDao = jyddDao;
    }

    @Autowired
    public void setGoodsesDao(GoodsesDao goodsesDao) {
        this.goodsesDao = goodsesDao;
    }

    @Autowired
    public void setXshtDao(XshtDao xshtDao) {
        this.xshtDao = xshtDao;
    }

    @Autowired

    public void setSkshService(SkshService skshService) {
        this.skshService = skshService;
    }

    @Autowired

    public void setTkmxDao(TkmxDao tkmxDao) {
        this.tkmxDao = tkmxDao;
    }

    @Autowired

    public void setHtmxDao(HtmxDao htmxDao) {
        this.htmxDao = htmxDao;
    }

    @Autowired
    public void setClxxDao(ClxxDao clxxDao) {
        this.clxxDao = clxxDao;
    }
}


